【问题标题】:UIView frame and bounds wrongUIView 框架和边界错误
【发布时间】:2016-09-13 15:28:08
【问题描述】:

我有一个 UIView 子类,我正在向其中添加一些 CALayers。我已通过情节提要将此 UIView 添加到我的视图中。由于某种原因,在 init(和 awakeFromNib 中)访问框架和边界始终是 (0, 0, 1000, 1000)。这是为什么呢?

class SliderView: UIView {
    let trackLayer = CAShapeLayer()

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // The bounds are wrong
        trackLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 15).cgPath

    }
}

【问题讨论】:

  • 尝试覆盖initWithFrame:
  • @rmaddy 我也这样做了。我的代码实际上是在一个从 coder 和 initWithFrame 调用的共享 init 方法中。但由于我将它添加到情节提要中,所以它只是被调用的编码器。
  • 在 layoutSubviews 中获取框架,在布局约束被应用之后。
  • @JamesP 可以。 LayoutSubviews 确实被多次调用
  • @Tometoyou,你能解决这个问题吗?即使我也面临同样的问题。

标签: ios swift


【解决方案1】:

我在 UITableViewCell 中遇到了同样的问题。 这种解决方法应该有效

override func drawRect(rect: CGRect) {
    super.drawRect(rect)
    customInit()
}

var initialized = false
func customInit(){
    if !initialized{
        initialized = true

    // Bounds will be good. Do your stuff here
    }
}

在您的情况下,它应该如下所示:

class SliderView: UIView {
    let trackLayer = CAShapeLayer()

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // The bounds are wrong
    }

    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
        customInit()
    }

    var initialized = false
    func customInit() {
        if !initialized {
            initialized = true

            // Bounds will be good.
            trackLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 15).CGPath
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 2011-01-01
    • 1970-01-01
    相关资源
    最近更新 更多