使用自动布局时,如何确定根视图中 UIView 的框架



我有一个UIView,我使用 auto layout 放置在窗口视图中。 但是,当我尝试在控制台中打印出UIView的帧时,我得到了零。 如何确定UIView的位置?

我想知道框架的原因是因为我想在显示多个 UIViews 时使用以下函数

func intersects(CGRect) -> Bool 返回两个矩形是否相交。

func contains(CGRect) -> Bool 返回第一个矩形是否包含第二个矩形。

 var margin: UILayoutGuide!
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.white
    margin = self.view.layoutMarginsGuide
    let sq1 = Square.init(color: UIColor.blue)
    self.view.addSubview(sq1)
    sq1.translatesAutoresizingMaskIntoConstraints = false
    sq1.heightAnchor.constraint(equalToConstant: 200).isActive = true
    sq1.widthAnchor.constraint(equalToConstant: 200).isActive = true
    sq1.topAnchor.constraint(greaterThanOrEqualTo: margin.topAnchor, constant: 20).isActive = true
    sq1.centerXAnchor.constraint(equalTo: margin.centerXAnchor).isActive = true
    print("sq1.frame: (sq1.frame)")
}

 class Square: UIView{
var colour: UIColor
init(color: UIColor) {
    self.colour = color
    super.init(frame: .zero)
    self.backgroundColor = color
}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

安慰:

sq1.frame: (0.0, 0.0, 0.0, 0.0)

在 vc 内部使用viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
    super.viewDidlayoutSubviews()
      print("sq1.frame: (sq1.frame)")
}

在视图的类内部

override func layoutSubviews() {
    super.layoutSubviews()
      print("self.frame: (self.frame)")
}

我认为最好的选择是等到调用layoutSubviews()。您可以使用类似于以下内容的代码:

 class Square: UIView{
    let colour: UIColor
    init(color: UIColor) {
        self.colour = color
        super.init(frame: .zero)
        self.backgroundColor = color
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        print("frame: (frame)")
    }
    required init?(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
    }
}

最新更新