Access UIView width at runtime

前端 未结 4 532
走了就别回头了
走了就别回头了 2021-02-05 01:21

In Swift, how do I get the width (or height) at runtime, of a UIView that\'s created programmatically using auto layout constraints?

I\'ve tried view1.frame.size.

相关标签:
4条回答
  • 2021-02-05 02:12

    Frame width and height returns zero because at the time you called that function inside of viewDidLoad it is not yet sized properly. You can use viewDidAppear to call your necessary functions

    0 讨论(0)
  • 2021-02-05 02:16

    Add this and you are good to go:

    override func viewDidLayoutSubviews() {
            println(self.view1.frame.size)
        }
    

    you can look at width or height as you please.

    0 讨论(0)
  • 2021-02-05 02:19

    you can only use this

    self.view1.frame.size.width
    self.view1.frame.size.height
    
    0 讨论(0)
  • 2021-02-05 02:26

    Just one thing about these fields:

    self.view1.frame.size.width
    self.view1.frame.size.height
    

    Are only actual user device size if the view has been drawn to screen, else they are what ever you set them as in the storyboard. So if your trying to perform some kind of calculation before the view is drawn you will have to figure out the width or height another way!

    0 讨论(0)
提交回复
热议问题