How to construct a ScrollView using Swift? How to construct a ScrollView using Swift? swift swift

How to construct a ScrollView using Swift?


Let's give this a shot. The one thing to note is I have yet to find a way to downcast self.view as a UIScrollView, so you can't make calls like self.view.contentOffset.

import UIKitclass ScrollingViewController : UIViewController {    // Create a scrollView property that we'll set as our view in -loadView    let scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)    override func loadView() {        // calling self.view later on will return a UIView!, but we can simply call         // self.scrollView to adjust properties of the scroll view:        self.view = self.scrollView        // setup the scroll view        self.scrollView.contentSize = CGSize(width:1234, height: 5678)        // etc...    }    func example() {        let sampleSubView = UIView()        self.view.addSubview(sampleSubView) // adds to the scroll view        // cannot do this:        // self.view.contentOffset = CGPoint(x: 10, y: 20)        // so instead we do this:        self.scrollView.contentOffset = CGPoint(x: 10, y: 20)    }}


Your outlet is not connected. From the Swift with objective-C book:

When you declare an outlet in Swift, the compiler automatically converts the type to a weak implicitly unwrapped optional and assigns it an initial value of nil. In effect, the compiler replaces @IBOutlet var name: Type with @IBOutlet weak var name: Type! = nil

If this value was not connected, it would remain as nil and you'd get a runtime error when accessing the value.


 @IBOutlet weak var scrollView: UIScrollView!    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        // setup the scroll view        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 200, 0);    }