开发者

How to make IBOutlets out of an array of objects?

I want to make an array with a bunch of UIImageViews I have in Interface Builder. Instead of having 20 or 30

IBOutlet UIImageView *img1;

and linking them all that way, and then pu开发者_JAVA技巧tting them into an array, is there a way to declare an array of IBOutlet UIImageViews?

Just so I don't have so many declarations in my header file.


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.


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

How to make IBOutlets out of an array of objects?


Swift 3 and above:

@IBOutlet var stuckLabels: [UIImageView]


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜