中心导航栏标题包含左右栏项目?

时间:2015-04-05 16:53:05

标签: ios swift uinavigationbar

我试图设置一个导航栏标题,但到目前为止我尝试过的每种方法都将标题移动得太远或视图根本没有加载并导致应用程序崩溃。这是我最近的尝试(app崩溃)

    let rightItemSize = self.navigationItem.rightBarButtonItem?.width
    let leftItemSize = self.navigationItem.leftBarButtonItem?.width

    let navWidth = self.navigationController?.navigationBar.frame.size.width
    let navHeight = self.navigationController?.navigationBar.frame.size.height


    let titleWidth = navWidth! - (rightItemSize! + leftItemSize!)

    let requiredPadding = rightItemSize! - leftItemSize!

    var titleViewToAdd = UIView(frame: CGRectMake(0, 0, titleWidth, navHeight!))
    var label = UILabel(frame: CGRectMake(requiredPadding, 0, titleWidth - requiredPadding, navHeight!))

    label.backgroundColor = UIColor.redColor()
    label.font = UIFont.boldSystemFontOfSize(14.0)
    label.textColor = UIColor.blackColor()
    label.numberOfLines = 1
    label.textAlignment = NSTextAlignment.Center

    label.text = "\(albumsArtist)"

    titleViewToAdd.addSubview(label)
    self.navigationItem.titleView = titleViewToAdd

如果我使用self.navigationItem.title =" \(albumsArtist)"。文本居中并且效果很好但最终我想要有两行文本,这种方法不起作用。

我知道这里有类似的问题和答案,但我所看到的所有问题都是针对Objective-C的,当我试图将它们转换为Swift时,效果并不好。

非常感谢!

1 个答案:

答案 0 :(得分:3)

管理以使其适用于此!

    let label = UILabel(frame: CGRect(x: 10, y: 0, width: 50, height: 40))
    label.backgroundColor = .red
    label.font = UIFont.boldSystemFont(ofSize: 14)

    label.text = "My title"
    label.numberOfLines = 2
    label.textColor = .black
    label.sizeToFit()
    label.textAlignment = .center

    self.navigationItem.titleView = label