Adding UITapGestureRecognizer in XIB

I created a custom XIB that extends from a UITableViewHeaderFooterView and is trying to add a gesture recognizer. The only problem is trying to add a recognizer through the result of the interface builder to the object being added to the top-level hierarchy, and the following error leading to the failure of my application:

The application terminated due to the uncaught exception "NSInternalInconsistencyException", reason: "invalid registered alias for identifier (AccordionHeader)). Nib must contain exactly one top-level object, which must be an instance of UITableViewHeaderFooterView"

As far as I know, there is no equivalent equivalent to "viewDidLoad" or I'm just adding the recognizer program code. Is there any other way to do this?

+5
source share
1 answer

You are right, the recognizer should not be added to the XIB at the top level.

My decision:

class SettingsUserAvatarHeader: UITableViewHeaderFooterView { // Set as a variable, as it will be re-created on cell re-use var tapGestureRecognizer = UITapGestureRecognizer() // This will be called every time the cell moves off screen and returns override func prepareForReuse() { super.prepareForReuse() // Needs to be done manually. tapGestureRecognizer = UITapGestureRecognizer() avatarImageView.gestureRecognizers = [ tapGestureRecognizer ] } // This will be needed for the first display override func didMoveToSuperview() { super.didMoveToSuperview() avatarImageView.gestureRecognizers = [ tapGestureRecognizer ] } } 

In doing so, you can listen to the taps directly. I am using RxSwift:

First add the extension for the tap:

 extension Reactive where Base: SettingsUserAvatarHeader { var avatarTap: ControlEvent<UITapGestureRecognizer> { return self.base.tapGestureRecognizer.rx.event.asControlEvent() } } 

And in your controller / delegation, etc .:

 class Consumer: UITableViewDelegate { var avatarTapDisposable: Disposable? override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "userAvatarView") let view = cell as! SettingsUserAvatarHeader avatarTapDisposable = view.rx .avatarTap .subscribe(onNext: { (tap) in // Here your code for the tap }) return cell } } 
0
source

Source: https://habr.com/ru/post/1241966/


All Articles