我有一个UIView
,我已使用auto layout
放置在窗口视图中。但是,当我尝试在控制台中打印出UIView
的框架时,我得到的归零值。如何确定UIView
的位置?
我想知道框架的原因是因为我想在显示多个UIView时使用以下功能
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)
答案 0 :(得分:0)
我认为最好的选择是等待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")
}
}
答案 1 :(得分:0)
在vc内使用viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidlayoutSubviews()
print("sq1.frame: \(sq1.frame)")
}
在视图类中
override func layoutSubviews() {
super.layoutSubviews()
print("self.frame: \(self.frame)")
}