导航集titleTextAttributes因swift3失败,Xcode 8.3

时间:2018-01-03 02:39:23

标签: ios swift uinavigationcontroller attributes uinavigationbar

我希望我的导航标题使用TruncationMiddle,例如" ABC ... XYZ" 。
我尝试这样做,但我失败了。
感谢。

self.title = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingMiddle

self.navigationController!.navigationBar.titleTextAttributes = [NSParagraphStyleAttributeName: paragraphStyle]


我的项目失败了 Link of my project in GitHub.

更新图片:

enter image description here

3 个答案:

答案 0 :(得分:0)

您实际上需要使用NSMutableParagraphStyle而不是NSParagraphStyle

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingMiddle

self.navigationController?.navigationBar.titleTextAttributes = [NSParagraphStyleAttributeName: paragraphStyle]

lineBreakMode属性有一个可以使用的setter,而不是直接使用NSParagraphStyle类和truncationMode键不允许的键设置值。

答案 1 :(得分:0)

尝试在导航栏中添加自定义标签。

let label = UILabel(frame: CGRect(x:0, y:0, width:400, height:50))
label.backgroundColor = UIColor.clear
label.numberOfLines = 1
label.font = UIFont.boldSystemFont(ofSize: 13.0)
label.textAlignment = .center
label.textColor = UIColor.black
label.lineBreakMode = .truncateMiddle

self.navigationItem.titleView = label 

// OR 

// self.navigationController!.navigationBar.topItem.titleView =  label

如果您愿意,您还可以在标签中显示多行,然后将numberOfLines设置为0,将换行模式设置为worldwrap:)

希望它有用

答案 2 :(得分:0)

您只需在代码中添加以下行:

    self.title = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    let navLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
    navLabel.text = self.title
    navLabel.textColor = .white
    navLabel.font = UIFont(name: "Helvetica-Bold", size: 14.0)
    navLabel.backgroundColor = .clear
    navLabel.adjustsFontSizeToFitWidth = false
    navLabel.lineBreakMode = .byTruncatingMiddle
    self.navigationItem.titleView = navLabel