gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:00:51 27 4
gpt4 key购买 nike

我正在尝试为带有“标题”和“描述”标签的导航 Controller 实现自定义 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()

我该如何解决这个问题?

最佳答案

我已经在导航栏中创建了标题和副标题,而无需界面生成器和约束修改。

我创建标题 View 的函数如下所示:

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
}

然后为了在任何 View Controller 中使用标题 View ,我只调用这一行:

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com