iosswiftuiviewcontrollerswift3iboutlet

Swift: Create an optional IBOutlet


I'm writing a UIViewController for others to inherit from. This UIViewController has a UIScrollView in it. Currently, I create the UIScrollView like this:

scrollView.contentSize = CGSize(width: viewWidth * 2, height: viewHeight)
scrollView.delegate = self
view.addSubview(scrollView)
view.sendSubview(toBack: scrollView)

This works, but to make the UIViewController extensible, I want to be able to have an IBOutlet for it that people can connect their UIScrollViews to from the storyboard.

If someone connected a UIScrollView via storyboard, I'd use that scrollView. Otherwise, I'd use the code above to make it myself.

I've seen this in a library before, but can't remember the library so I can't reference how to do it.


Solution

  • Just create an outlet:

    @IBOutlet var scrollView: UIScrollView!
    

    In viewDidLoad, if scrollView is nil, that means the outlet is not connected. You can check this using a simple if statement:

    if scrollView == nil {
        scrollView = UIScrollView(...)
        scrollView.contentSize = CGSize(width: viewWidth * 2, height: viewHeight)
        scrollView.delegate = self
        view.addSubview(scrollView)
        view.sendSubview(toBack: scrollView)
    }
    // do the things you want to do with the scroll view here.