Question

I have a top list view in my current iPhone app, that's populated by code. I've assembled the view using Interface Builder, so it contains lot of UILabels.

Obviously I wouldn't like to have name1, name2, etc. outlets in my class, but prefer a name[10] array.

Is it possible to do so, and connect each item to the appropriate label (or any other interface builder like view)?

Was it helpful?

Solution

you cannot do it in IB, but you can create an array in your init method and add all your labels to it.

BTW, you can set some tag to each label and define macro to access it. smth like

#define NAME[TAG] (UILabel*)[self.view viewWithTag:TAG]

OTHER TIPS

You can of course do this with interface builder, the keyword is IBOutletCollection. What it does is basically an NSArray out of multiple interface builder outlets.

IBOutletCollection(UILabel) NSArray *myLabels;

So the next thing would be connecting your labels in interface builder and then you can use the array to access all labels at runtime.

This can be done using outlet collections, see this related question.

Follow these steps to create an array of outlets an connect it with IB Elements (Here is example of UIView, you can use UILabel also):

  • 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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top