Search code examples
swiftuikit

attach several UILabels from storyboard to one IBOutlet


I've 15 Labels in my Storyboard they are just texts, also set from storyboard, What I want to do is to style them, but programitically, Therefore I need to create 15 IBOutlets in my ViewController, I wonder if there is any other way of doing that, without 15 IBOutlets,if it's possible to create 1 IBOutlet and attach all of them to that one? because creating 15 of them is kinda stressing...


Solution

  • You can do this with Outlet Collections instead of an IBOutlet for all the labels you want to group together:

    What I like to do is to create the specific outlet collection in code first if I way to track the same type like so:

    @IBOutlet var labelCollection: [UILabel]!

    The I drag from the editor to the storyboard

    IBOutlet Collection XCode multiple UIViews UILabels

    Then I can work with it as follows

    @IBOutlet var labelCollection: [UILabel]!
    
    func setCustomLayout()
    {
        for label in labelCollection
        {
            // do your customization here
        }
    }
    

    Then you can loop through the UIViews inside the IBOutletCollection and do the needful

    Based on this answer, it seems like you could also have multiple types in a single outlet collection.