我想提出我的问题,希望有人能帮助我:
我创建了 UINavigationBar 的子类,添加图像作为背景。
这是代码:
class NavigationBarN: UINavigationBar {
let customHeight: CGFloat = UIScreen.main.bounds.height / 8
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
translatesAutoresizingMaskIntoConstraints = true
self.barStyle = UIBarStyle.black
self.tintColor = .white
}
override init(frame: CGRect) {
super.init(frame: frame)
translatesAutoresizingMaskIntoConstraints = true
self.barStyle = UIBarStyle.black
self.tintColor = .white
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: customHeight)
}
var i = 0
override open func layoutSubviews() {
super.layoutSubviews()
frame = CGRect(x: frame.origin.x, y: 0, width: frame.size.width, height: customHeight) // problem here
for subview in self.subviews {
var stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarBackground") {
subview.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: customHeight))
imageViewBackground.image = UIImage(named: “Image”1)
imageViewBackground.contentMode = .scaleToFill
subview.addSubview(imageViewBackground)
}
stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarContent") {
let centerY = subview.frame.heigh
subview.frame = CGRect(x: subview.frame.origin.x, y: centerY, width: subview.frame.width, height: subview.frame.height)
}
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
直到iOS 11,它都可以正常工作,因为iOS 12开始出现问题,子类进入无限循环。然而,只有当我尝试通过“navigationController?.PushViewController”函数初始化一个新的VC时,才会发生无限循环,否则它会起作用。
导致循环的代码行显然是:
frame = CGRect(x: frame.origin.x, y: 0, width: frame.size.width, height: customHeight)
但是删除它,导航栏不会正确创建。
大家有什么解决办法吗?
谢谢
最佳答案
您不应该在 layoutSubviews
中更改框架 - 您应该只布置 subview 。更改 layoutSubviews
中框架的大小会耦合 View 的布局和大小,但您不应该这样做。
很可能在幕后,UINavigationBar
在其框架设置时调用 setNeedsLayout
。
关于ios - 子类 UINavigationBar SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62272657/