Need some help cleaning up a bit of my code
I have 5 buttons named opt1, opt2, opt3, etc. If I want to hide/show/do something to them, could I create a simple for statement instead of doing opt1.hidden = YES, opt2.hidden....? If so, what would it look like? Thanks
EDIT: This is the code I am trying to clean:
opt1.hidden = NO;
opt2.hidden = NO;
opt3.hidden = NO;
opt4.hidden = NO;
opt5.hidden = NO;
Is there a simple for statement I could use that would hide all of them without having to hide each one manually since the only difference in their name is the number at the end? It doesn't seem 开发者_如何学运维like a lot of buttons but I will have to add lots more soon so I would rather not have 20 lines of code just to hide a bunch of buttons.
You can do this.
NSArray *myButtons = [NSArray arrayWithObjects:b1, b2, b3, b4, nil];
for (UIButton *button in myButtons)
{
button.hidden = YES;
}
David's suggestion is a good one if you know and have a pointer to all your buttons.
An alternative would be to loop through all of your UIView subviews and hide buttons as you find them:
for (id subview in self.view)
{
if ([subview isKindOfClass:[UIButton class]])
[(UIButton*)subview setHidden:YES];
}
If you want to be selective with the buttons you are hiding, simply add a specific tag to it upon creation (i.e. button1.tag = 999
) and use:
for (id subview in self.view)
{
if ([subview isKindOfClass:[UIButton class]] && subview.tag == 999)
[(UIButton*)subview setHidden:YES];
}
David's answer is probably best, and is how I would do it for a small number of controls. You could also use KVC.
NSArray *myButtons = [NSArray arrayWithObjects:@"b1", @"b2", @"b3", @"b4", nil];
for (NSString *str in myButtons)
{
id cont = [self valueForKey:key] ;
if ([cont isKindOfClass:[UIButton class]]) {
[cont setHidden:YES] ;
}
}
The reason I am showing you this method is it can be used to create "bindings" between a DB and your controls. Imagine if the myButtons array contained the names of DB fields. You could then name your UI controls in your controller with the same name. Then all you need is a simple for loop, and maybe some isKindOfClass test, to move all the control data into your DB. Here is an example from one of my projects.
NSArray *fn = [AOSConfig sharedInstance].fieldNames ;
for (NSString* name in fn) {
@try {
id uifield = [self valueForKey:name] ;
if ([cont isKindOfClass:[UITextField class]]) {
[aosShotData setValue:[uifield valueForKey:@"text"] forKey:name]
}
}
@catch(NSException *e) {
}
}
That's it to save all the text data to a CoreData managed object. You would need to get creative if you need various data types. If the DB is complex in terms of the data type to control mapping it may be better to just write it brute force.
精彩评论