Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 602
David Avatar asked Oct 16 '25 21:10

David


1 Answers

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.
like image 56
Sweeper Avatar answered Oct 18 '25 12:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!