Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift put multiple IBOutlets in an Array

Multiple IBOutlets

I made these (marked with red border) IBOutlets using ctrl + drag

But i don't like to have the exact same line 9 times (DRY)

How do i put these IBOutlets in an Array?

like image 772
cor Avatar asked Jul 17 '14 13:07

cor


2 Answers

you can define a generic outlet collection in Swift like this:

@IBOutlet var collectionOfViews: Array<UIView>? // = [UIView]? 

or for e.g. UIButton objects:

@IBOutlet var collectionOfButtons: Array<UIButton>? // = [UIButton]? 

you can find your collections under the Outlet Collections group as usually are in the File's Owner:

Outlet Collections

it would look on my console after connecting 5 random buttons:

Connected UIButton instances to Collection

like image 143
holex Avatar answered Sep 27 '22 16:09

holex


Follow these steps to create an array of outlets an connect it with IB Elements:

  • Create an array of IBOutlets
  • Add multiple UIElements (Views) in your Storyboard ViewController interface
  • Select ViewController (In storyboard) and open connection inspector
  • There is option 'Outlet Collections' in connection inspector (You will see an array of outlets there)
  • Connect if with your interface elements

-

class ViewController2: UIViewController {       @IBOutlet var collection:[UIView]!       override func viewDidLoad() {         super.viewDidLoad()     } } 

enter image description here

like image 38
Krunal Avatar answered Sep 27 '22 17:09

Krunal