[英]How to fetch the width and height of a programatically added view in Swift/ iOS?
I have added a UIView and a UIImageView programatically, but I need its width and height.我以编程方式添加了 UIView 和 UIImageView,但我需要它的宽度和高度。 Is it possible to fetch it, if yes, please share how to fetch it.是否可以获取它,如果可以,请分享如何获取它。
Code:代码:
let View1: UIView = {
let viewView = UIView()
viewView.translatesAutoresizingMaskIntoConstraints = false
viewView.contentMode = .scaleAspectFit
print(UserDefaults.standard.bool(forKey: "backgroundColourSelected"))
if UserDefaults.standard.bool(forKey: "backgroundColourSelected") {
viewView.backgroundColor = self.viewColor
}else {
viewView.backgroundColor = .white
}
viewView.clipsToBounds = true
return viewView
}()
self.canvasView.addSubview(View1)
View1.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor, constant: 0).isActive = true
View1.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor, constant: 0).isActive = true
View1.widthAnchor.constraint(equalTo: canvasView.widthAnchor, constant: 0).isActive = true
View1.heightAnchor.constraint(equalTo: canvasView.widthAnchor, multiplier: aspectRatio).isActive = true
use override func viewWillLayoutSubviews() for ViewController and override func layoutSubviews() for UIView.对 ViewController 使用覆盖 func viewWillLayoutSubviews() 并为 UIView 使用覆盖 func layoutSubviews()。
Example: - for UIViewControllers示例:- 用于 UIViewControllers
override func viewWillLayoutSubviews() {
print(yourView.frame.height)
}
for UIViews对于 UIViews
override func layoutSubviews() {
print(yourView.frame.height)
print(yourView.frame.width)
}
Since your view is inside the function just move it out由于您的视图在 function 内部,只需将其移出
class YourController / YourView {
private let imgView: UIImageView = {
let iv = UIImageView()
// do whatever you want with your image using iv. eg. iv.contentMode = .scaleAspectFit or iv.image = UIImage(named: "custom_img")
return iv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imgView)
//set constraints for your
}
// then use layoutSubViews(for views) / viewWillLayoutSubViews (for controller) and calculate the height
} }
You need to know the life cycle of view controller.你需要知道视图controller的生命周期。
To get height of any view use viewDidLayoutSubviews
.要获得任何视图的高度,请使用viewDidLayoutSubviews
。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(view1.frame.size)
}
size
property will print both final height and width. size
属性将打印最终高度和宽度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.