【问题标题】:Best place to make a UIView subclass round进行 UIView 子类回合的最佳场所
【发布时间】:2022-11-01 12:18:36
【问题描述】:

我有一个需要圆形的 UIView 子类。我遇到的问题是 此视图使用框架 .zero 实例化(并最终调整大小),当在初始化程序中调用 makeRound 时,会产生一个为 0 的 cornerRadius

我应该调用哪个 UIView 生命周期方法 makeRound 并假设 layer.bounds 已采用其最终值(非零)?

fileprivate extension UIView {
    func makeRound() {
        layer.cornerRadius = layer.bounds.width*0.5
        clipsToBounds = true
    }
}

我可以使用的唯一 UIView 子类初始化程序是

    public init() {
        super.init(frame: .zero)
        // init routines
    }

【问题讨论】:

    标签: swift uikit


    【解决方案1】:

    我要么覆盖bounds 属性,要么覆盖layoutSubviews 方法。

    class SomeView: UIView {
        // Either do this:
        override var bounds: CGRect {
            didSet {
                layer.cornerRadius = bounds.size.height / 2.0
                // or call makeRound()
            }
        }
    
        // Or do this:
        override func layoutSubviews() {
            super.layoutSubviews()
    
            layer.cornerRadius = bounds.size.height / 2.0
            // or call makeRound()
        }
    }
    

    不要两者都做。选择两者之一。

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      相关资源
      最近更新 更多