Search code examples
iosswiftuinavigationcontrolleruinavigationbaruinavigationitem

Navigation item in my UIViewController is overlapping child views and labels


I am adding custom navigation item to my application. But every time I navigate the items of navigation item overlaps. My code is

    func fixNavBar(){
        self.navigationItem.setHidesBackButton(true, animated: true)
        let nav = self.navigationController?.navigationBar
        let navView = UIView(frame: CGRect(x: 0, y: 0, width: (nav?.frame.width)!, height: (nav?.frame.height)!))
        let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: navView.frame.height, height: navView.frame.height))
        backButton.imageView?.contentMode = .scaleToFill
        backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        backButton.setTitleColor(UIColor(rgb: 0x23C0FF), for: .normal)
        backButton.tintColor = UIColor(rgb: 0x23C0FF)
        nav?.addSubview(navView)
        backButton.addTarget(self, action: #selector(goBack), for: .touchUpInside)
        navView.backgroundColor = .clear
        let imageView = UIImageView(frame: CGRect(x: backButton.frame.width+5, y: 0, width: navView.frame.height-2, height: navView.frame.height-2))
        let profUrl = URL(string: "\(selectedUser.profilePictuer)")
        imageView.kf.setImage(with: profUrl)
        let userLbl = UILabel(frame: CGRect(x: backButton.frame.width + 15 + imageView.frame.width, y: 0, width: 150, height: navView.frame.height))
        userLbl.font = UIFont(name: UIFont.fontNames(forFamilyName: "Ubuntu")[0], size: 17)
        userLbl.text = selectedUser.fullName
        userLbl.textAlignment = .left
        userLbl.textColor = .black
        navView.addSubview(imageView)
        navView.addSubview(userLbl)
        navView.addSubview(backButton)
        imageView.layer.cornerRadius = imageView.frame.height/2
        imageView.layer.masksToBounds = true
    }

    @objc func goBack(sender: UIButton!) {
        self.navigationController!.popViewController(animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        fixNavBar()
    }

This is root view controller when where I select any chat to open Chats screen

When I select chat for first time I get something like that First chat opened

And when select second chat it does not remove previous user's name but overlaps it Second chat opened


Solution

  • Your root and child view controller has the same navigationcontroller so when everytime you call fixNavBar , some views appending on the previous .

    First option is adding nav?.subviews.forEach({$0.removeFromSuperview()}) on the top of your function like @Raja's comment.

    Second is go storyboard and embed a new navigationController to your child viewcontroller(where yout function is)