在iOS开发中,navigationBarTitle
默认情况下会占用导航栏的全宽。如果你想要防止这种情况,可以通过自定义导航栏标题视图来实现。以下是一些常见的方法:
你可以创建一个自定义的 UIView
,并在其中放置一个 UILabel
,然后将这个自定义视图设置为导航栏的标题视图。
// 创建一个自定义标题视图
let titleLabel = UILabel()
titleLabel.text = "Your Title"
titleLabel.textColor = .black
titleLabel.font = UIFont.boldSystemFont(ofSize: 18)
titleLabel.sizeToFit()
// 设置自定义标题视图
navigationItem.titleView = titleLabel
如果你不想使用自定义视图,可以尝试调整标题的对齐方式,使其居中显示。
// 设置标题居中
navigationItem.titleView = UIView()
navigationItem.title = "Your Title"
你也可以使用 attributedTitle
属性来设置标题,并通过 attributed string 来调整标题的对齐方式。
let titleString = NSMutableAttributedString(string: "Your Title")
titleString.addAttribute(.paragraphStyle, value: NSParagraphStyle(), range: NSRange(location: 0, length: titleString.length))
titleString.addAttribute(.paragraphStyle, value: NSTextAlignment.center, range: NSRange(location: 0, length: titleString.length))
navigationItem.titleView = UIView()
navigationItem.attributedTitle = titleString
你还可以使用 UIBarButtonItem
来设置标题,并通过自定义视图来实现居中显示。
let titleItem = UIBarButtonItem(customView: titleLabel)
navigationItem.setLeftBarButton(titleItem, animated: true)
navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped)), animated: true)
这些方法适用于需要在导航栏中显示自定义标题的场景,例如:
通过上述方法,你可以有效地防止 navigationBarTitle
占用全宽,并根据具体需求选择合适的方式来实现自定义标题视图。这些方法不仅提升了界面的美观性,还增强了用户体验。
领取专属 10元无门槛券
手把手带您无忧上云