navBar.setTitleVerticalPositionAdjustment(CGFloat(7), forBarMetrics: UIBarMetrics.Default)
UIView
对象,在其中添加UIButton
和UILabel
以显示类似视图。将此自定义视图添加到导航控制器的左侧栏按钮项中。override func viewDidLoad() {
super.viewDidLoad()
var customView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 44.0))
customView.backgroundColor = UIColor.yellow
var button = UIButton.init(type: .custom)
button.setBackgroundImage(UIImage(named: "hamburger"), for: .normal)
button.frame = CGRect(x: 0.0, y: 5.0, width: 32.0, height: 32.0)
button.addTarget(self, action: #selector(menuOpen(button:)), for: .touchUpInside)
customView.addSubview(button)
var marginX = CGFloat(button.frame.origin.x + button.frame.size.width + 5)
var label = UILabel(frame: CGRect(x: marginX, y: 0.0, width: 65.0, height: 44.0))
label.text = "Inbox"
label.textColor = UIColor.white
label.textAlignment = NSTextAlignment.right
label.backgroundColor = UIColor.red
customView.addSubview(label)
var leftButton = UIBarButtonItem(customView: customView)
self.navigationItem.leftBarButtonItem = leftButton
}
func menuOpen(button: UIButton) {
// Handle menu button event here...
}
您还可以像这样设置导航栏外观titlePositionAdjustment
:
let a = UINavigationBarAppearance()
a.titlePositionAdjustment = .init(
horizontal: -CGFloat.greatestFiniteMagnitude,
vertical: 0
)
navigationItem.scrollEdgeAppearance = a
navigationItem.compactAppearance = a
navigationItem.standardAppearance = a
另一种解决方法是将标题缩进:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 72
navigationBar.titleTextAttributes = [
.foregroundColor: UIColor.purple,
.paragraphStyle: paragraphStyle
]
您可以将自定义视图设置为导航项的左/右侧栏项目。
请参考以下示例:
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: viewModal.getNavBarTitleView())
[viewModal.getNavBarTitleView()
返回一个水平堆栈视图,其中包含一个 imageView 和一个 label。]
设置左对齐的自定义视图。
将自定义视图设置为leftBarButtonItem并不方便,因为我们会遇到返回按钮的问题。
将自定义视图作为navigationBar的子视图设置也不方便,因为:
所以呢? 我刚刚将宽度约束添加到了customTitleView中。
在CustomTitleView类内部:
private func layoutViewsConfig() {
// Width constraint needed to align view to left
let widthConstraint = NSLayoutConstraint.init(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.width)
widthConstraint.priority = .init(748)
let heightConstraint = NSLayoutConstraint.init(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
self.addConstraint(widthConstraint)
self.addConstraint(heightConstraint)
}
然后,在您的ViewController内部:
var navigationTitleView = NavigationSubtitleView()
self.navigationItem.titleView = navigationTitleView
我们有: