Reputation: 821
I have a UITableViewCell file and inside of it I do:
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)
}
where
private var kvoContext = 0
So, I want: When I click on the button in those Cell it'll run function from the ViewController. But on click on my button does not print anything.
It's my first time with KVOs, am I doing something wrong?
Upvotes: 2
Views: 1413
Reputation: 1167
Well, KVO does not work like that. What - addObserver:forKeyPath:options:context:
does is register observer to receive KVO notifications when property changed. In your case I suppose "followerButtonTapped" is not a property. Registering for observation
To handle button tapped you need to add target like this (or in IB):
cell.followerButton.addTarget(self, action: #selector(ViewController.onFollowerButtonTap(_:)), forControlEvents: .TouchUpInside)
And add method to your view controller:
func onFollowerButtonTap(sender: UIButton) {
}
To get the model object for this button you can use this extension:
extension UITableView {
func indexPathForView(view: UIView) -> NSIndexPath? {
let hitPoint = view.convertPoint(CGPoint.zero, toView: self)
return indexPathForRowAtPoint(hitPoint)
}
}
Upvotes: 1