【问题标题】:Issue with clicking vertically aligned Bar Buttons outside of the Navigation Bar单击导航栏外垂直对齐的栏按钮时出现问题
【发布时间】:2021-12-04 12:31:33
【问题描述】:

我试图在我的UINavigationBar 的右侧垂直对齐两个UIBarButtonItems。我正在使用自定义视图,并在其中对齐两个按钮。

代码如下:

let rightBarButtonCustomView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 90))
        
        let settingsButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        settingsButton.setImage(UIImage(systemName: "gearshape.fill"), for: .normal)
        settingsButton.backgroundColor = preferredBackgroundColor
        settingsButton.tintColor = .accentColor
    
        settingsButton.addTarget(self, action: #selector(openSettingsScreen), for: .touchUpInside)
        settingsButton.layer.cornerRadius = settingsButton.frame.size.height / 2
        settingsButton.layer.borderWidth = 1
        settingsButton.layer.borderColor = UIColor.label.cgColor
        settingsButton.layer.masksToBounds = true
        
        rightBarButtonCustomView.addSubview(settingsButton)
        
        //NotificationButton
        let notificationsButton = UIButton(frame: CGRect(x: 0, y: 50, width: 40, height: 40))
        notificationsButton.setImage(UIImage(systemName: "bell.fill"), for: .normal)
        notificationsButton.backgroundColor = preferredBackgroundColor
        notificationsButton.tintColor = .accentColor

        notificationsButton.addTarget(self, action: #selector(openNotificationScreen), for: .touchUpInside)
        notificationsButton.layer.cornerRadius = notificationsButton.frame.size.height / 2
        notificationsButton.layer.borderWidth = 1
        notificationsButton.layer.borderColor = UIColor.label.cgColor
        notificationsButton.layer.masksToBounds = true
        
        rightBarButtonCustomView.addSubview(notificationsButton)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButtonCustomView)

这是它的样子:

不错吧?

嗯,问题是通知按钮没有收到点击,但设置按钮是。我的猜测是通知按钮在导航栏之外,如图(UINavigationBar是蓝色的,我的rightBarButtonCustomView是红色的):

我尝试使用约束,增加导航栏的高度,但似乎没有任何效果。

任何帮助将不胜感激

谢谢!

【问题讨论】:

  • 根据您的图像,您似乎没有在导航控制器堆栈中?如果是这种情况,您最好使用UINavigationBar。如果您位于导航控制器堆栈中(也就是说,您通过“推送”它来访问此视图控制器),请显示您用于设置导航栏外观的代码。

标签: ios swift uinavigationbar uibarbuttonitem nslayoutconstraint


【解决方案1】:

下面的代码对我来说效果很好。

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    navigationBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 200)
}

【讨论】:

  • 高度正常不到一秒,马上又恢复正常。我应该做一个不同的视图功能吗? (即 viewDidLoad() 或 viewDidAppear())
  • 嗨@goatofanerd 你是在真机还是模拟器上测试??
  • 真机!这有关系吗?
  • 是的。设备操作系统也很重要。请在您的模拟器上查看。
  • 遗憾的是相同的结果:(如果你愿意,我可以附上结果的视频。让我试着把你的代码放在不同的视图函数中
猜你喜欢
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多