3

I am trying to access view.frame.size.height and view.frame.size.width outside a function, and I am not able to. Is there any workaround for this?

I tried doing this, but it did not work-

 var screenBound = UIScreen.mainScreen().bounds
    var screenSize = screenBound.size
    var screenWidth = screenSize.width
    var screenHeight = screenSize.height

Xcode gave me an error- Instance member 'screenbound' cannot be used on type 'ViewController'

I can only use self.view.frame.size.height/.width inside a created function. But I want to use it outside a function. Thanks in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    Most probably a duplicate of [How to initialize properties that depend on each other](http://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other). – Martin R Apr 11 '16 at 18:59
  • @MartinR I didn't quite get it. Could you post some code as to how I could use it in this case? Thanks :) – user5981057 Apr 11 '16 at 19:08
  • @MartinR I got that I cannot use a variable outside a function, because it self.variable is not really initialised, and so you can use the lazy keyword as the newly created variable is used later. But in this case, I'm having difficulty creating the lazy variable because the self.view is not initialised. – user5981057 Apr 11 '16 at 19:13

1 Answers1

3

I'm not sure what exactly you're trying to do, but couldn't you just put this at the global level (i.e. above "class ViewController..."):

let screenWidth = UIScreen.mainScreen().bounds.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height

Then you can access these anywhere in your project.

36 By Design
  • 3,203
  • 3
  • 18
  • 18