简体   繁体   中英

Determine width of UIView in Swift

I have an autolayouted UIView and need to know the width of it. How do I find the width the easiest way in Swift?

You can find the width of any view by

 let width = yourView.bounds.width

If you have applied a width constraint to the view and you have an outlet for that constraint then you can find it by.

let width = yourWidthConstraint.constant

The right place to get the UIScreen frame data is in viewDidLayoutSubviews as it is called after the subViews have been laid out in screen also it is called after every time your device changes orientation such as your width will be different when your user goes into landscape mode.This is called after viewWillAppear :

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let viewWidth = self.myView.bounds.width

  }

Inside implementation your view you can use

override func layoutSubviews() {
    super.layoutSubviews()
    // you can get width of view in this function
    print(self.frame.size.width)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM