我尝试动态设置导航栏的文字,以便标题文字始终适合。我正是这样完成的:
// 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
}
然而,正如此图所示,这会将标题文本降低到其自然高度以下:
左侧的导航栏来自我应用的其他视图,而右侧的导航栏是我设置的一个。
这两个导航栏都是我拖动的导航栏,并使提示等于空字符串以增加其高度:
任何人都可以帮我实现上面的代码,以便它不会删除标题文本吗?
**编辑:以下是Xcode调试层次结构的截图:
这是正常的导航栏:
这是我设置的那个:
答案 0 :(得分:0)
您需要设置基线,默认为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
}
}