How to make IBOutlets out of an array of objects?

╄→尐↘猪︶ㄣ 提交于 2019-11-30 08:07:54

It is possible, it’s called outlet collection. This is the way to define an outlet collection:

@property(retain) IBOutletCollection(UIImageView) NSArray *images;

Now you can stick more than one object into the outlet in the Interface Builder, the array will be created for you when the interface is loaded.

I'm a little late here but it may be easier to set the tag property of each ImageView in IB, then access them like [some_superview viewWithTag:tag] rather than keep a separate handle to each one.

Iztik Goeta

Swift 3 and above:

@IBOutlet var stuckLabels: [UIImageView]

Here is more easier way to do it.

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()
    }
}

There's not, unfortunately, but you can keep all of the declarations on a single line:

IBOutlet UIImageView *img1, *img2, *img3, *img4;

The other option (probably best, since you have so many of these) would be to create them programatically and store them in an array, then add them to the view from your view controller class, using, for each,

[self.view addSubview:img];

Also, keep in mind that if the elements are static (like background elements), and you don't actually need to access them, you don't need to declare outlets for each; you can just add them to the nib file and forget about them.

Same goes for UIButton instances. If you don't need to change anything about the button, you can access it from the method that it calls, like so:

-(IBAction) buttonPressed:(id)sender {
    UIButton *button = (UIButton *)sender;
    // method guts
    // stuff with button -- access tag, disable, etc
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!