Search code examples
iosswiftuinavigationbaruinavigationitem

Setup rightBarButtonItem in navigationBar


I have stuck on this bug for days. I have a problem with rightBarButtonItem. I want to create a custom view. Inside custom view, there are 2 items: label, imageView. When I type this:

let customView = UIView()
    customView.translatesAutoresizingMaskIntoConstraints = false
    customView.backgroundColor = .black
    customView.frame = CGRect(x: 0, y: 0, width: 90, height: 40)

    let coinLabelNavigationBar = UILabel()
    coinLabelNavigationBar.frame = CGRect(x: 40, y: 0, width: 30, height: 25)
    coinLabelNavigationBar.translatesAutoresizingMaskIntoConstraints = false
    coinLabelNavigationBar.text = "200"
    coinLabelNavigationBar.font = UIFont(name: ".SFUIText-Medium", size: 20)
    coinLabelNavigationBar.textColor = UIColor.white

    let coinImage = UIImageView()
    coinImage.frame = CGRect(x: 75, y: 0, width: 25, height: 25)
    coinImage.translatesAutoresizingMaskIntoConstraints = false
    coinImage.image = UIImage(named: "Coin")

    customView.addSubview(coinLabelNavigationBar)
    customView.addSubview(coinImage)

    let rightBarButton = UIBarButtonItem(customView: customView)

    navigationItem.rightBarButtonItem = rightBarButton

It doesn't work, navigationBar shows me this: NavBar

Do you have any idea, how to fix it?

Thanks for your answers.


Solution

  • try this -

    let customView = UIView()
    //        customView.translatesAutoresizingMaskIntoConstraints = false
        customView.backgroundColor = .black
        customView.frame = CGRect(x: 0, y: 0, width: 90, height: 40)
    
        let coinLabelNavigationBar = UILabel()
        coinLabelNavigationBar.frame = CGRect(x: 40, y: 0, width: 30, height: 25)
    //        coinLabelNavigationBar.translatesAutoresizingMaskIntoConstraints = false
        coinLabelNavigationBar.text = "200"
        coinLabelNavigationBar.font = UIFont(name: ".SFUIText-Medium", size: 20)
        coinLabelNavigationBar.textColor = UIColor.white
    
        let coinImage = UIImageView()
        coinImage.frame = CGRect(x: 75, y: 0, width: 25, height: 25)
     //        coinImage.translatesAutoresizingMaskIntoConstraints = false
        coinImage.image = UIImage(named: "coin.jpg")
    
        customView.addSubview(coinLabelNavigationBar)
        customView.addSubview(coinImage)
    
        let rightBarButton = UIBarButtonItem(customView: customView)
    
        navigationItem.rightBarButtonItem = rightBarButton