我有一个 UITableViewCell 文件,我在里面做:
var followers: FollowersModel? {
didSet {
self.followerButton.addObserver(self, forKeyPath: "followerButtonTapped", options: .New, context: &kvoContext)
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
print(keyPath)
}
在哪里
private var kvoContext = 0
所以,我想要:当我单击那些 Cell 中的按钮时,它将从 ViewController 运行功能。但是单击我的按钮不会打印任何内容。
这是我第一次使用 KVO,我做错了什么吗?
最佳答案
嗯,KVO 不是那样工作的。 - addObserver:forKeyPath:options:context:
所做的是注册观察者以在属性更改时接收 KVO 通知。在你的情况下,我想“followerButtonTapped”不是一个属性。 Registering for observation
要处理点击的按钮,您需要像这样(或在 IB 中)添加目标:
cell.followerButton.addTarget(self, action: #selector(ViewController.onFollowerButtonTap(_:)), forControlEvents: .TouchUpInside)
并将方法添加到您的 View Controller :
func onFollowerButtonTap(sender: UIButton) {
}
要获取此按钮的模型对象,您可以使用此扩展:
extension UITableView {
func indexPathForView(view: UIView) -> NSIndexPath? {
let hitPoint = view.convertPoint(CGPoint.zero, toView: self)
return indexPathForRowAtPoint(hitPoint)
}
}
关于ios - 如何正确地将 Key-Value Observer 添加到我的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36693582/