How can one address controls dynamically in obj-c?
For instance I have created a view with 50 sequential buttons named btn1-btn50. If I want to ad开发者_如何学编程dress these buttons and make some changes to them in a loop how can I address the controls with a string name?
The typical way to get a view in a hierarchy is to call [parentView viewWithTag:] to get the view. If you give the buttons tag values from 1 to 50 you can use that to access the buttons.
If for some reason you need strings, you will have to create a custom subclass of UIButton that has a name member, assign a name to that member, then later iterate through the view hierarchy searching for an instance of your custom class with a name matching your search criteria.
If you have given them a tag
, you can access them conveniently using -viewWithTag:
on the parent view.
You have no guarantee that these buttons are laid out in memory sequentially, so trying to use pointer arithmetic is probably out. But you can get all the subviews of an NSView with -subviews
, and just do something with the NSButtons:
for (NSView *view in [theView subviews]) {
if (![view isKindOfClass:[NSButton class]]) continue;
/// you got a button!
}
In your View Contoller add an NSMutableDictionary *buttonViews property. In your viewDidLoad method, add each button to buttonViews using the name string as the key and the button as the object. You will have to use viewWithTag: already discussed to obtain the views. Now you can locate the button using the string and benefit from the collection methods and fast enumeration. Apple's documentation for Interface Builder indicates that the "name" in IB is used to assist identifying objects in IB which is helpful for translation.
精彩评论