我正在尝试动态设置导航栏的文本,以便标题文本始终适合。我是这样完成的:
// Pet's Day text "Joy's Day"
if let range = currentPet.range(of: "_") {
let petsName = currentPet[range.upperBound..<currentPet.endIndex]
let deviceWidth = UIScreen.main.bounds.size.width
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: deviceWidth, height: 40))
titleLabel.text = "\(petsName)'s Day"
titleLabel.font = UIFont.systemFont(ofSize: 30)
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.white
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = 0.5
titleLabel.textAlignment = .center
self.navBar.topItem?.titleView = titleLabel
}
但是,如图所示,这会将标题文本降低到其自然高度以下:
左侧的导航栏来 self 的应用程序的其他 View 之一,而右侧的导航栏是我正在设置的 View 。
这两个导航栏都是我拖入的导航栏,并将提示设置为空字符串以增加其高度:
任何人都可以帮我实现上面的代码,这样它就不会下拉标题文本吗?
**编辑:以下是 Xcode 调试层次结构的屏幕截图:
这是正常的导航栏:
这是我正在设置的:
最佳答案
需要设置基线,默认是Align Baseline
,需要改为Align Centers
代码示例:
class TestViewController: UIViewController {
@IBOutlet weak var navBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
// Change the height of the navbar
self.navBar.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 68)
let deviceWidth = UIScreen.main.bounds.size.width
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: deviceWidth, height: 40))
titleLabel.text = "Log Events" // Change to Joy's Day and check the result
titleLabel.font = UIFont.systemFont(ofSize: 30)
titleLabel.baselineAdjustment = .alignBaselines
titleLabel.textColor = UIColor.white
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = 0.5
titleLabel.textAlignment = .center
self.navBar.topItem?.titleView = titleLabel
}
}
关于ios - 为什么设置 titleView 会降低标题文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45775428/