Variable IBOutlet name for a UILabel?

心不动则不痛 提交于 2019-12-04 02:38:43

问题


Ugh, having some trouble here...

I have 4 display labels in Interface Builder set up as IBOutlets in the view controller.

I've set them up with these names label1, label2, label3, label4

I'm want to change the label text for a randomly selected label

I'm trying this...

In the header file I declare as a property:

@property (nonatomic retain) UILabel *myLabel;

And then in my implementation file I synthesize and I'm trying

myLabel = [UILabel valueForKey: [NSString stringWithFormat:@"label%d", randomInt]];

myLabel.text = @"bleh!";

The myLabel = [UILabel ... line is causing to crash. Any help? Thanks!


回答1:


You have the right idea, but you should pass valueForKey: to self, not UILabel, assuming its self that owns these properties.

myLabel = [self valueForKey:[NSString stringWithFormat:@"label%d", randomInt]];

As a side note, this is probably better done with an IBOutletCollection. In Xcode 4, select all of the labels and drag them to the header file. This will generate an IBOutletCollection NSArray containing all the outlets. You can then pick a random index from that array. It is usually unfortunate that IBOutletCollection stores its outlets in a non-deterministic order, but for your case it should be fine.



来源:https://stackoverflow.com/questions/7232911/variable-iboutlet-name-for-a-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!