Search code examples
swiftuiviewuisegmentedcontrolxcode9swift4

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.


Solution

  • 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