假设我有UIView
的自定义UIButton
。此按钮的目标可以引用自定义UIView
的父视图中的选择器吗?甚至从实现视图传递选择器?我试过以下没有运气:
class CustomView: UIView {
var button = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
let buttonSize = min(frame.height, frame.width)/2.0
self.button = UIButton(frame: CGRectMake(0.0, 0.0, buttonSize, buttonSize))
self.button.setTitle("Example Title", forState: .Normal)
self.button.center = self.center
self.addSubview(button)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addTargetToButton(selector: Selector) {
self.button.addTarget(self, action: selector, forControlEvents: .TouchUpInside)
}
}
我希望使用类似这样的东西来创建一个菜单,其中包含未定义数量的按钮,这些按钮都可以在实现UIViewController
中被赋予目标。这将是VC的基本语法:
private extension Selector {
static let actionIWantTapped = #selector(CustomViewController.actionIWant(_:))
}
class CustomViewController: UIViewController {
var customView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
customView = UIView(frame: self.view.frame)
customView.addTargetToButton(.actionIWantTapped)
}
func actionIWant(sender: UIButton!) {
// do something
}
}