Reputation: 387
As the question states, when I tried to set an image view inside a UIView class, to have a corner Radius of its frame height divided by 2, it wasn't working, so I decided to print the frame height and it was 0.
The height or width for every view in this class prints 0 I don't know why... Thanks in advance for your answers.
Upvotes: 0
Views: 4148
Reputation: 387
I found the problem. When calling the UI View class i wasn't passing by parameter the actual frame of this view. So when this class initializer was executed the frame was always 0.
Upvotes: 1
Reputation: 722
By default a view will have no size whatsoever. You have to set some sort of constraints or the view's frame.
1. Constraints:
When setting constraints in viewDidLoad()
, the view will not instantly gain a size. In order to read the size, you'll have to read it in another function called viewDidLayoutSubviews()
. This function is called after all views were laid out. Here is an example where the view will gain the size of its parent view:
var newView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
newView = UIView()
newView!.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(newView!)
newView!.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
newView!.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
newView!.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
newView!.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
override func viewDidLayoutSubviews() {
print(newView!.frame)
}
2. Frame: By setting the views frame directly, you can instantly read its size. Here is an example where the view's frame is set to the same bounds as its parent view:
var newView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
newView = UIView()
newView?.frame = view.bounds
newView!.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(newView!)
print(newView!.frame)
}
Upvotes: 0