【问题标题】:Subclass UINavigationBar SWIFT子类 UINavigationBar SWIFT
【发布时间】: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)

但删除它,导航栏创建不正确。

有人有解决办法吗?

谢谢

【问题讨论】:

    标签: ios swift iphone xcode


    【解决方案1】:

    你不应该在layoutSubviews 中改变你的框架——你应该只布置你的子视图。在layoutSubviews 中更改框架的大小会影响视图的布局和大小,这是您不应该做的。

    很可能在后台,UINavigationBar 在其框架设置时正在调用setNeedsLayout

    【讨论】:

    • 谢谢!我已经尝试了一个明显的函数 setNeedsLayout,并在 setNeedsLayout 函数下分配框架值,正确创建了视图,但是无法与 BarButtomItem 元素交互。即使它们被显示,点击存在也不会产生任何效果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    相关资源
    最近更新 更多