在 init 中获取 UIView 的大小

Getting size of UIView in init

我在我的 iOS 应用程序中创建了 UIView 的自定义子类,我试图在视图的 init 方法中获取视图的计算大小,因此我可以在创建子视图时使用它们来放置在自定义视图中。

自定义视图在堆栈视图中,它为我的视图分配了总(主视图)高度的 1/3。

我的初始化看起来像这样:

var mySubView: UIImageView

required init?(coder aDecoder: NSCoder) {

    mySubView = UIImageView()
    super.init(coder: aDecoder)

    let viewWidth = Int(self.frame.size.width)
    let viewHeight = Int(self.frame.size.height)
    mySubView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
    mySubView.backgroundColor = UIColor.cyan

    self.addSubview(mySubView)
}

但是,未正确报告高度和宽度。例如,上面的 mySubView 最终只填充了自定义视图总数 space 的大约一半。

如有任何帮助,我们将不胜感激!

除非您事先知道确切的尺寸,否则在视图的生命周期中调用初始化程序的时间过早,无法准确地进行布局。即便如此,这也是错误的地方。

尝试使用 layoutSubviews 方法:

class SubView: UIImageView {

    var mySubView: UIImageView

    required init?(coder aDecoder: NSCoder) {

        mySubView = UIImageView()
        mySubView.backgroundColor = UIColor.cyan

        super.init(coder: aDecoder)
        self.addSubview(mySubView)
    }

    override func layoutSubviews() {
        mySubView.frame = self.bounds
        super.layoutSubviews()
    }
}

现在子视图边界将在每个布局过程开始时正确设置。这是一个廉价的操作。

此外,UIViewbounds 属性 是转换为视图内部坐标 space 的 frame。这意味着通常这是真的:bounds = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)。我建议阅读有关视图布局的文档。

或者,您可以完全放弃手动布局并使用 AutoLayout 为您完成此操作。

class SubView: UIImageView {

    var mySubView: UIImageView

    required init?(coder aDecoder: NSCoder) {

        mySubView = UIImageView()
        mySubView.backgroundColor = UIColor.cyan

        super.init(coder: aDecoder)
        self.addSubview(mySubView)

        mySubView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        mySubView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        mySubView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
        mySubView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
    }
}