nasxlf
nasxlf

Reputation: 45

Get the actual width of a subview at runtime (Swift 4)

Xcode provides a Segmented Control but I want a Custom Segmented Control with a selector that slides to each button when you press it. I use 3 views for it. One is the "main" view which I added two subviews. One of the subviews is the selector (UIView) and the other one is a UIStackView which contains the buttons. I use selector = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width/CGFloat(buttons.count), height: self.frame.height)) for the size of the selector. When I use my class for a view in the storyboard everything looks fine. I made constrains for the superview, but when I start the app with a simulator I get the width which was set in the storyboard and not the actual width at runtime with self.frame.width.

I used this video as a template. And here is what it looks like when I run the app. The selector is not as big as one button and that's why I get this white bar on the right site.

Upvotes: 3

Views: 2322

Answers (2)

Kassem Itani
Kassem Itani

Reputation: 1147

UIControl inherits from UIView class which you can use layoutSubviews function for getting correct Frame after constraints applied

override func layoutSubviews() {
     super.layoutSubviews()
    //self.frame will be correct here
}

references:

https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews https://developer.apple.com/documentation/uikit/uicontrol

Upvotes: 4

Kassem Itani
Kassem Itani

Reputation: 1147

Its looks like you are getting the frame before the Constraints are set, try getting the frame viewDidLayoutSubviews or viewDidAppear event

below are the events and the Constraints status:

  • viewDidLoad -- Constraints haven't set
  • viewWillAppear -- Constraints haven't set
  • viewWillLayoutSubviews -- Constraints are setting
  • viewDidLayoutSubviews -- Constraints are set
  • viewDidAppear -- Constraints are set

Upvotes: 2

Related Questions