Search code examples
iosswiftscrollviewcgfloatcgsize

Swift ScrollView - contentSize can't take a variable Int


Trying to set a scrollView's contentSize and I've run across this issue (Xcode 6.4)...

Both of these work perfectly:

scrollView.contentSize = CGSize(width:self.view.frame.width, height:1000)

scrollView.contentSize = CGSizeMake(self.view.frame.width, 1000)

Once a let (or var) gets involved, these do not work:

let testing = 1000
scrollView.contentSize = CGSize(width:self.view.frame.width, height:testing)

Error: Cannot find an initializer for type 'CGSize' that accepts an argument list of type '(width: CGFloat, height: Int)'

let testing = 1000
scrollView.contentSize = CGSizeMake(self.view.frame.width, testing)

Error: Cannot invoke 'CGSizeMake' with an argument list of type '(CGFloat, Int)'


Solution

  • Change the let statement to the following:

    let testing:CGFloat = 1000
    

    You need to do this as the CGSizeMake function requires two parameters of the same type, so you can either make both ints or make them both CGFloats. In this case it is probably easier to use testing as a CGFloat in the first place. In other cases, you might want to try something like

    let testing = 1000
    scrollView.contentSize = CGSizeMake(Int(self.view.frame.width), testing)
    

    Or:

    let testing = 1000
    scrollView.contentSize = CGSizeMake(self.view.frame.width, CGFloat(testing))
    

    So that both are of the same type.