我的 UIViewController 中的导航项与子视图和标签重叠

Navigation item in my UIViewController is overlapping child views and labels

我正在向我的应用程序添加自定义导航项。但是每次我导航导航项重叠的项目。我的密码是

    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()
    }

当我 select 打开任何聊天时,这是根视图控制器

当我 select 第一次聊天时,我得到了类似的东西

并且当 select 第二次聊天时它不会删除以前用户的名字但会重叠它

您的根视图控制器和 child 视图控制器具有相同的导航控制器,因此当您每次调用 fixNavBar 时,一些视图会附加到前一个 .

第一个选项是在您的函数顶部添加 nav?.subviews.forEach({[=11=].removeFromSuperview()}),就像@Raja 的评论一样。

其次是转到故事板并将新的导航控制器嵌入到您的 child viewcontroller(您的函数所在的位置)