iosswiftuikituinavigationbaruinavigationitem

How to detect touches on far right edge of navigation bar


I have a UIBarButtonItem assigned to navigationItem.rightBarButtonItems, and I would like the user to be able to tap all the way over to the right edge and have it respond. The Apple Notes app does this. The area I would like to be able to receive touches is in green below.

I have tried a custom view with trailing constraints beyond the superview, and it shows the view in that area, but does not respond to touches there. I have also tried creating a button overriding point(inside:,with:) to look for touches in a larger frame, but that does not respond to touches in that area either.

enter image description here


Solution

  • I added the button in the following unsophisticated way to the navigationBar and pressing it works.

    class ViewController2: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = .blue
            navigationController?.navigationBar.backgroundColor = .red
            navigationItem.rightBarButtonItems = [UIBarButtonItem(image: .add, style: .done, target: nil, action: nil)]
            let button = UIButton()
            button.translatesAutoresizingMaskIntoConstraints = false
            button.backgroundColor = .green
            button.addTarget(self, action: #selector(buttonDidTap), for: .touchUpInside)
            guard let navigationController else { return }
            navigationController.navigationBar.addSubview(button)
            NSLayoutConstraint.activate([
                button.topAnchor.constraint(equalTo: navigationController.navigationBar.topAnchor),
                button.bottomAnchor.constraint(equalTo: navigationController.navigationBar.bottomAnchor),
                button.trailingAnchor.constraint(equalTo: navigationController.navigationBar.trailingAnchor),
                button.widthAnchor.constraint(equalToConstant: 10)
            ])
        }
        
        @objc func buttonDidTap() {
            print("TAP")
        }
    }
    

    enter image description here