views:

69

answers:

4

For instance I have created a view with 50 sequential buttons named btn1-btn50. If I want to address these buttons and make some changes to them in a loop how can I address the controls with a string name?

+1  A: 

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!
}
kevingessner
`s/return/continue/`?
Georg Fritzsche
This may work because I can just loop through all of them looking for the one with the proper name, but is there no way to pass in a string to retrieve the view without looping through all of them?
Smallinov
@Georg, yes, thanks! Fixed it.
kevingessner
+2  A: 

If you have given them a tag, you can access them conveniently using -viewWithTag: on the parent view.

Georg Fritzsche
+3  A: 

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.

drawnonward
A: 

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.

falconcreek