Home > database >  Button action does not react when .touchUpInside inside a navigation bar
Button action does not react when .touchUpInside inside a navigation bar

Time:09-30

I created a UICollectionViewController to simulate a Feed app and I wanted to configure the top navigation bar similar to the Twitter one, with custom buttons that trigger actions, here's mine

enter image description here

The problem I'm facing is that when I click on the black profile icon, the action is not triggered.

Here's my code:

import UIKit

class HomeViewController: UICollectionViewController {

  //MARK: - Properties

  private lazy var profileButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(systemName: "person.fill"), for: .normal)
        button.tintColor = UIColor(rgb: 0x79CBBF)
        button.addTarget(self, action: #selector(didTapProfile), for: .touchUpInside)
        return button
    }()
    
     // MARK: - Lifecycle
    
  override func viewDidLoad() {
        super.viewDidLoad()
        setupNavBar()
    }
    
    // MARK: - Helpers
    
  func setupNavBar() {
        let width = view.frame.width
        let titleView = UIView()
        titleView.backgroundColor = .clear
        titleView.frame = .init(x: 0, y: 0, width: width, height: 50)
        
        titleView.addSubview(profileButton)
        
        profileButton.tintColor = .black
        profileButton.centerY(inView: titleView, leftAnchor: titleView.leftAnchor, paddingLeft: 0)
        
        
        titleView.addSubview(filterButton)
        filterButton.centerY(inView: titleView, leftAnchor: profileButton.rightAnchor,          paddingLeft: view.frame.width - 60 - 16)
        navigationItem.titleView = titleView
    }
    
   // MARK: - Actions
   @objc func didTapProfile() {
       print("did tap profile")
    }

As said below, I added a .addTarget to the button but the #selector(didTapProfile) function does not get triggered when the button is inside the navigation bar.

Any hints on how to do this?

CodePudding user response:

Instead of creating a title view and measuring its size and stuff... there are a load of convenience functions for doing this...

Take a look here... https://www.hackingwithswift.com/example-code/uikit/how-to-add-a-bar-button-to-a-navigation-bar

You can do something like...

navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(didTapProfile))

There are different ways to create UIBarButtonItem with images and text also...

https://developer.apple.com/documentation/uikit/uibarbuttonitem

  • Related