我在做this教程。由于 this,我必须修复我的代码问题。导航栏呈现如下图。我只需要我的标题图标位于导航栏的中心。有什么技巧吗?
这是我当前的代码。
func setUpNavigationBarItems(){
//https://www.youtube.com/watch?v=zS-CCd4xmRY
let titleImageView = UIImageView(image: UIImage(named: "ic_nav_app_icon"))
titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
titleImageView.contentMode = .scaleAspectFit
navigationItem.titleView = titleImageView
let addButton = UIButton(type: .system)
let addImage = UIImage(named: "ic_nav_add")
addButton.setImage(addImage?.withRenderingMode(.alwaysOriginal), for: .normal)
NSLayoutConstraint(item: addButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
NSLayoutConstraint(item: addButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: addButton)
let searchButton = UIButton(type: .system)
let searchImage = UIImage(named: "ic_nav_phone")
searchButton.setImage(searchImage?.withRenderingMode(.alwaysOriginal), for: .normal)
NSLayoutConstraint(item: searchButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
NSLayoutConstraint(item: searchButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
let settingButton = UIButton(type: .system)
let settingImage = UIImage(named: "ic_nav_setting")
settingButton.setImage(settingImage?.withRenderingMode(.alwaysOriginal), for: .normal)
NSLayoutConstraint(item: settingButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
NSLayoutConstraint(item: settingButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true
navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: searchButton), UIBarButtonItem(customView: settingButton)]
navigationController?.navigationBar.backgroundColor = .white
}
最佳答案
如果你替换它应该有正确的布局:
titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
与:
NSLayoutConstraint(item: titleImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 34).isActive = true
NSLayoutConstraint(item: titleImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 34).isActive = true
如前一个答案中所述,标题 View 的框架在运行时可能不是 34x34。相反,它部分取决于图像的大小(UIImageView 的固有内容大小取决于图像的大小)和 UINavigationBar 的自动布局配置。
如果您运行 View 调试器,您可能会看到标题 View 的框架类似于 150x44,这就是为什么它被偏移到一侧以便为 UINavigationBar 中的所有内容腾出空间。
View 调试工具位于 Xcode 的底部栏中(在调试区域的顶部):
它可以让您检查框架、约束和更多的 View 层次结构,并且通常会提示您在遇到此类问题时可能出了什么问题。
关于ios - 多个navigationItem.rightBarButtonItem时,navigationItem.titleView无法居中渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54967202/