自定义titleView在推送后更改位置并在堆栈中弹出新屏幕

时间:2017-09-27 13:05:42

标签: ios swift uikit

我正在尝试使用“title”和“description”标签为导航控制器实现自定义titleView。如果我将这个titleView放在第一个VC上,它看起来不错。如果我将第二个VC推入导航堆栈并弹出它,则会更改titleView的位置。

titleView的约束:

titleLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
descriptionLabel.widthAnchor.constraint(equalTo: titleLabel.widthAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 2.0).isActive = true

在VC的viewDidLoad中,我使用关注代码插入titleView

navigationItem.titleView = BarTitleView()
navigationItem.titleView?.bounds = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
navigationItem.titleView?.updateConstraints()

我尝试将跟随行插入viewWillAppear(第二个VC有不同的栏按钮,它可能是问题的根源),但没有任何变化

navigationItem.titleView?.bounds = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
navigationItem.titleView?.updateConstraints()

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我在导航栏中创建了标题和副标题,无需使用Interface Builder和约束修改。

我创建标题视图的功能如下所示:

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

    titleLabel.backgroundColor = UIColor.clear
    titleLabel.textColor = UIColor.white
    titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
    titleLabel.text = title
    titleLabel.sizeToFit()

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

    // Fix incorrect width bug
    if (subtitleLabel.frame.size.width > titleLabel.frame.size.width) {
        var titleFrame = titleLabel.frame
        titleFrame.size.width = subtitleLabel.frame.size.width
        titleLabel.frame = titleFrame
        titleLabel.textAlignment = .center
    }

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

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

    if widthDiff < 0 {
        let newX = widthDiff / 2
        subtitleLabel.frame.origin.x = abs(newX)
    } else {
        let newX = widthDiff / 2
        titleLabel.frame.origin.x = newX
    }

    return titleView
}

然后在任何视图控制器中使用标题视图我只需要调用此行:

self.navigationItem.titleView = Functions.Views.setTitle(title: "Title String", subtitle: "Subtitle String")