iOS 11 - Navigationbar大标题自定义偏移量

时间:2017-10-24 11:31:14

标签: swift uinavigationcontroller uinavigationbar ios11 uinavigationitem

是否可以更改大导航栏标题的x偏移量?我想将x偏移更改为36pt。

The navigation bar

4 个答案:

答案 0 :(得分:6)

您可以通过以下方式添加其他偏移量:

if #available(iOS 11.0, *) {
    let navigationBarAppearance = UINavigationBar.appearance()
    let style = NSMutableParagraphStyle()
    style.alignment = .justified
    style.firstLineHeadIndent = 18
    navigationBarAppearance.largeTitleTextAttributes = [NSAttributedStringKey.paragraphStyle: style]
}

答案 1 :(得分:4)

我刚刚在最新版本的iOS 12中发现,如果您仅修改layoutMargins的{​​{1}}属性,就会影响大标题。

UINavigationBar

我尝试了此处提到的有关使用自定义let navigationBar = navigationController.navigationBar navigationBar.layoutMargins.left = 36 navigationBar.layoutMargins.right = 36 的解决方案。确实确实可以,但是因为它延伸了由大标题组成的NSMutableParagraphStyle视图,所以当您向下滑动时,在文本略微增长的地方播放的细微动画会变得相当失真。

答案 2 :(得分:2)

你做不到。您需要编写自己的NavigationController,方法是为其创建UINavigationController。

答案 3 :(得分:0)

你必须继承UINavigationBar,然后覆盖draw方法,并在里面进行更改。看看我的工作示例,然后根据需要调整偏移/样式:

    override func draw(_ rect: CGRect) {
    super.draw(rect)

    self.backgroundColor = UIColor.white
    let largeView = "_UINavigationBarLargeTitleView"
    let labelcolor = UIColor(red: 36.0/255.0, green: 38.0/255.0, blue: 47.0/255.0, alpha: 1.0)

    for view in self.subviews {
        if largeView.contains(String(describing: type(of: view))) {
            for v in view.subviews {
                if String(describing: type(of: v)) == "UILabel" {
                    var titleLabel = v as! UILabel
                    var labelRect = titleLabel.frame
                    let labelInsets = UIEdgeInsets(top: 10, left: 13, bottom: 0, right: 0)
                    let attrText = NSMutableAttributedString(string: "Jobs", attributes: [NSAttributedStringKey.font: UIFont(name: "SFProDisplay-Heavy", size: 30)!, NSAttributedStringKey.foregroundColor: labelcolor])

                    labelRect.origin.y += 20
                    let newLabel = UILabel(frame: labelRect)
                    newLabel.attributedText = attrText
                    titleLabel.text = ""
                    if labelRect.origin.y > 0 {
                        titleLabel = newLabel
                        titleLabel.drawText(in: UIEdgeInsetsInsetRect(labelRect, labelInsets))
                    }
                }
            }
        }
    }
}