我需要扩展我的导航栏高度,但由于Apple在iOS 11中更改导航栏高度非常困难,我决定使用自定义视图扩展导航栏,而无需用户注意。
我已创建自定义视图以添加到导航栏的底部。我把它变成红色只是为了让这个问题更清楚。当用户离开视图控制器然后返回时,标题视图自定义视图被剪切"由红色视图。为什么呢?
我已尝试在自定义标题视图中设置clipsToBounds
false,但这并没有帮助。如何确保自定义标题视图始终位于所有内容之上?为什么它被小红色视图剪切和重叠(其主要目的是"扩展"导航栏)?
注意:"每月支出" label是要剪切的标题视图的一部分。
class ViewController: UIViewController {
let customTitleView = CustomTitleView()
let navigationBarExtensionView: UIView = {
let view = UIView()
view.backgroundColor = .red
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setupAdditionalGradientView()
navigationItem.titleView = customTitleView
}
internal func setupAdditionalGradientView() {
view.addSubview(navigationBarExtensionView)
navigationBarExtensionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
navigationBarExtensionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
navigationBarExtensionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
navigationBarExtensionView.heightAnchor.constraint(equalToConstant: 18).isActive = true
// Hide pixel shadow between nav bar and red bar
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.layer.shadowRadius = 0
navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 0)
}
}
自定义标题视图:
import UIKit
class CustomTitleView: UIView {
let primaryLabel: UILabel = {
let label = UILabel()
label.text = "$10,675.00"
label.font = UIFont.systemFont(ofSize: 27.99, weight: .medium)
label.textColor = .white
label.textAlignment = .center
return label
}()
let secondaryLabel: UILabel = {
let label = UILabel()
label.text = "Monthly Spending"
label.textColor = .white
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 10, weight: .medium)
return label
}()
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fillProportionally
stackView.alignment = .center
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupStackView()
}
internal func setupStackView() {
addSubview(stackView)
stackView.addArrangedSubview(primaryLabel)
stackView.addArrangedSubview(secondaryLabel)
stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 10).isActive = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
答案 0 :(得分:1)
在iOS 11中,使用约束从内到外调整自定义栏按钮项目视图(例如titleView
)。因此,您需要约束来正确调整视图大小。您没有提供任何约束,因此运行时不知道如何调整标题视图的大小。
但是,我建议您放弃将UINavigationItem的自定义视图向下扩展到导航栏外部下方的可疑想法,而只是在视图控制器的视图中显示“每月支出”字样。