我正在尝试使用“标题”和“描述”标签为导航控制器实现自定义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()

如何解决此问题?

最佳答案

我已经在导航栏中创建了标题和副标题,而无需进行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")

关于ios - 自定义titleView在推送并在堆栈中弹出新屏幕后更改位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46448695/

10-10 20:44