【发布时间】: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