如何通过swift3设置navigationTitleView和Truncate标签的宽度

时间:2017-07-20 01:53:26

标签: ios swift uinavigationcontroller uinavigationbar titleview

我有关于导航titleView的问题 titleView覆盖我右边的barbuttonItem并且在屏幕之外 我在中心区域需要titleView,并且barbuttonItem有正确的区域 我想知道如何设置标题的宽度,因为我无法成功设置宽度 而且我也想截断标签的中间位置 我怎么了?
感谢。

Here is Image about my question.
Here is Image about my question.

self.navigationItem.titleView = setTitle(title: name, subtitle: "")


func setTitle(title:String, subtitle:String) -> UIView {
    let titleLabel = UILabel(frame: CGRect(x:0, y:5, width:0, height:0))

    titleLabel.backgroundColor = UIColor.clear
    titleLabel.textColor = UIColor.white
    titleLabel.font = defaultTitleFont
    titleLabel.text = title
    titleLabel.sizeToFit()

    let subtitleLabel = UILabel(frame: CGRect(x:5, y:18, width:0, height:0))
    subtitleLabel.backgroundColor = UIColor.clear
    subtitleLabel.textColor = UIColor.red
    subtitleLabel.font = UIFont.systemFont(ofSize: 20)
    subtitleLabel.text = subtitle
    subtitleLabel.sizeToFit()

    let titleView = UIView(frame: CGRect(x:0, y:0, width:max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height:35))
    titleView.addSubview(titleLabel)
    //titleView.addSubview(subtitleLabel)

    let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width

    if widthDiff > 0 {
        var frame = titleLabel.frame
        frame.origin.x = widthDiff / 2
        titleLabel.frame = frame.integral
    } else {
        var frame = subtitleLabel.frame
        frame.origin.x = abs(widthDiff) / 2
        subtitleLabel.frame = frame.integral
    }

    return titleView
}

1 个答案:

答案 0 :(得分:0)

您必须事先计算标题视图大小/帧。 一种可能的方法是考虑屏幕宽度和导航栏中显示的条形按钮项目数。

看看下面的代码(简化为仅显示标题,没有副标题):

func getTitleView (title:String, numOfButtons: Int = 0) -> UIView {
    let barButtonSize = 70
    let offset: CGFloat = CGFloat(numOfButtons * barButtonSize)
    let frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width - offset, height: 35)
    let titleView = UIView(frame:frame)

    let titleLabel = UILabel(frame: titleView.bounds)

    titleLabel.backgroundColor = UIColor.clear
    titleLabel.textColor = UIColor.red
    titleLabel.font = UIFont.systemFont(ofSize: 14)
    titleLabel.text = title
    titleLabel.numberOfLines = 1
    titleLabel.textAlignment = .center
    titleLabel.lineBreakMode = .byTruncatingMiddle
    titleView.addSubview(titleLabel)
    return titleView
}

来自viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: nil)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: nil)

    self.navigationItem.titleView = getTitleView(title: "Wow Wow Wow Wow Wow Wow Wow Wow Wow Wow Wow Wow Wow Wow Wow WowWow Wow Wow Wow Wow Wow Wow WowWow WowWowWowWowWowWowWowWow Wow Wow Wow Wow Wow Wow Wow!!", numOfButtons: 2)
}

输出: enter image description here