Home > Net >  attach several UILabels from storyboard to one IBOutlet
attach several UILabels from storyboard to one IBOutlet

Time:01-26

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...

CodePudding user response:

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

One way to do it is to ctrl drag from your storyboard to your editor and select outlet collection

IBOutlet Collection XCode

This will create @IBOutlet weak var labelCollection: UILabel! in your code

This works fine but then you need to add an additional check for the type when looping:

@IBOutlet weak var labelCollection: UILabel!

func setCustomLayout()
{
    for label in labelCollection2.subviews
    {
        if let label = label as? UILabel
        {
            // do your custom set up here
        }
    }
}

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

  •  Tags:  
  • Related