【发布时间】:2020-06-08 23:18:13
【问题描述】:
我想提出我的问题,希望有人可以帮助我:
我创建了一个 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)
但删除它,导航栏创建不正确。
有人有解决办法吗?
谢谢
【问题讨论】: