Search code examples
iosswiftxcodeuibarbuttonitem

addGestureRecognizer to rightBarButtonItem with customView


How I can add action to my rightBarButtonItem with customView?

Now I have code:

override func viewDidLoad() {
    super.viewDidLoad()
    configurePhotoProfile()
}

func configurePhotoProfile() {
    let imageView = UIImageView()
    let widthConstraint = imageView.widthAnchor.constraint(equalToConstant: 34)
    let heightConstraint = imageView.heightAnchor.constraint(equalToConstant: 34)
    heightConstraint.isActive = true
    widthConstraint.isActive = true
    imageView.kf.setImage(with: URL(string: channel?.recipientUrlImage ?? ""))
    imageView.backgroundColor = .clear
    imageView.layer.masksToBounds = true
    imageView.layer.cornerRadius = 17
    imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(ChatsViewController.didTapImageButton(_:))))
    if UserDefaults.standard.integer(forKey: UserDefaultsKeys.selectedSegmentedControl) == 0 {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: imageView)
    } else {
        self.navigationItem.rightBarButtonItem = nil
    }
}

@objc func didTapImageButton(_ sender: UIBarButtonItem) {
    print("tap")
}

But if I tap on barButtonItem I can't see my print("tap") in console. Where is my problem?


Solution

  • Use UITapGestureRecognizer like below

    let tap = UITapGestureRecognizer(target: self, action: #selector(ChatsViewController.didTapImageButton(_:)))
    tap.numberOfTapsRequired = 1
    imageView.addGestureRecognizer(tap)