【问题标题】:Custom button in navigation bar - added and gets tapped but not visible导航栏中的自定义按钮 - 添加并被点击但不可见
【发布时间】:2026-01-07 12:45:02
【问题描述】:

我尝试在导航控制器中添加自定义后退按钮。我创建这样的按钮

    func setupBackButton() {
    let backButton = UIButton.init(type: .custom)
    backButton.addTarget(self, action: #selector(backButtonHandler(_:)), for: .touchUpInside)
    backButton.setTitleColor(UIColor.white, for: .normal)
    backButton.setTitle("<", for: .normal)
    backButton.tintColor = UIColor.white
    let barBackButton = UIBarButtonItem(customView: backButton)
    self.navigationItem.leftBarButtonItem  = barBackButton
}

问题是正在添加按钮(我可以点击它并执行按钮上的操作)但我在控制器中看不到按钮 - 它是不可见的。

控制器的颜色是蓝色的。

【问题讨论】:

  • 只需将框架分配给您的按钮。

标签: ios uinavigationcontroller swift3


【解决方案1】:

你错过了按钮的框架

backButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)

别忘了添加动作处理程序

func backButtonHandler(_ sender : UIButton)  {

}

【讨论】:

    【解决方案2】:

    试试这个:

    func setupBackButton(){
        let backBtn : UIBarButtonItem = UIBarButtonItem(title: "<", style: UIBarButtonItemStyle.plain, target: self, action:#selector(backToPreviousVC))
        self.navigationItem.leftBarButtonItem = backBtn
        backBtn.tintColor = UIColor.white
    }
    
    func backToPreviousVC() {
        self.navigationController?.popViewController(animated: true)
    }
    

    在 viewDidLoad 中调用 setupBackButton()

    【讨论】: