ios - 子类 UINavigationBar SWIFT

标签 ios swift iphone xcode

我想提出我的问题,希望有人能帮助我:

我创建了 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/

相关文章:

ios - Storyboard的 Swift 输入和事件处理

xcode - Foundation.framework 图标呈红色,并且由于 Xcode 8 Beta,Cocoapod 的路径不正确。我知道正确的路径,但无法设置它

ios - 释放Core Foundation对象

iphone - 我可以从 fetchedResultsController 中删除对象而不从数据库中删除该对象吗?

ios - UIView中的圆两个角

ios - Xcode如何自动完成动态方法

ios - Ionic 1 应用程序 - 尝试从 Cordova dataDirectory 提供图像文件

SwiftUI:如何持久化 @EnvironmentObject 变量?

Swift - 使用用户密码加密和解密字符串

ios - 自定义对象初始化器