Skip to content

Instantly share code, notes, and snippets.

@el-hoshino
Created October 23, 2015 05:57
Show Gist options
  • Save el-hoshino/d049c8eb1b28c3daa448 to your computer and use it in GitHub Desktop.
Save el-hoshino/d049c8eb1b28c3daa448 to your computer and use it in GitHub Desktop.
UIButton の動作を Callback で設定する方法 ref: http://qiita.com/lovee/items/65b1f10313454fca4a05
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?()
}
}
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
}
}
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