Created
October 23, 2015 05:57
-
-
Save el-hoshino/d049c8eb1b28c3daa448 to your computer and use it in GitHub Desktop.
UIButton の動作を Callback で設定する方法 ref: http://qiita.com/lovee/items/65b1f10313454fca4a05
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class CallbackButton: UIButton { | |
private var action: (() -> Void)? | |
init(frame: CGRect, action: (() -> Void)? = nil) { | |
self.action = action | |
super.init(frame: frame) | |
self.addTarget(self, action: "tapped:", forControlEvents: .TouchUpInside) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
func setAction(action: () -> Void) { | |
self.action = action | |
} | |
func tapped(sender: CallbackButton) { | |
self.action?() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeView: UIView { | |
var a = 1 | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
let button = UIButton(frame: CGRectZero) | |
button.addTarget(self, action: "tapped:", forControlEvents: .TouchUpInside) | |
self.addSubview(button) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
func tapped(sender: UIButton) { | |
self.a *= 2 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeView: UIView { | |
var a = 1 | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
let button = CallbackButton(frame: CGRectZero) { () -> Void in | |
self.a *= 2 | |
} | |
self.addSubview(button) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment