ios - 为什么设置 titleView 会降低标题文本?

标签 ios swift uinavigationbar

我正在尝试动态设置导航栏的文本,以便标题文本始终适合。我是这样完成的:

// 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
}

但是,如图所示,这会将标题文本降低到其自然高度以下:

pic

左侧的导航栏来 self 的应用程序的其他 View 之一,而右侧的导航栏是我正在设置的 View 。

这两个导航栏都是我拖入的导航栏,并将提示设置为空字符串以增加其高度:

pic2

pic2

任何人都可以帮我实现上面的代码,这样它就不会下拉标题文本吗?

**编辑:以下是 Xcode 调试层次结构的屏幕截图:

这是正常的导航栏:

pic4

这是我正在设置的:

pic5

最佳答案

需要设置基线,默认是Align Baseline,需要改为Align Centers

enter image description here

代码示例:

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/

相关文章:

ios - 无法将我的 objective-c 类的基类设置为 swift 类

ios - NSInvalidArgumentException,使用 performSegueWithIdentifier 时发送到实例的无法识别的选择器

ios - 在多个 ViewController 之间访问/传递公共(public)数据

ios - 无法将 CollectionViewCell 移动到末尾

ios - 如何在某些情况下设置具有标题 View 的导航项的标题

iOS 7 View 布局和半透明效果

ios - 第一次点击位于 tableviewcell 内的第二个 UITextfield 没有开始编辑(显示光标)。只有第二次点击有效。为什么?

ios - 通过cocoapod安装CorePlot 2.0失败

iphone - UIAnimation 导致按钮 titleLabel 在动画期间消失

ios - 自 iOS 11 以来 RefreshControl 刷新后的粘性 UINavigationbar