Reputation: 235
I have a project that contains 35 identical buttons (with black background and gray border) located one beside the other (5 in the first row, then five more in the bottom, fill up my whole screen of iphone).
The way in which I am putting the edges is:
button1.layer.borderWidth = 1.0f;
button1.layer.borderColor = [[UIColor grayColor] CGColor];
button2.layer.borderWidth = 1.0f;
button2.layer.borderColor = [[UIColor grayColor] CGColor];
button3.layer.borderWidth = 1.0f;
button3.layer.borderColor = [[UIColor grayColor] CGColor];
....
button35.layer.borderWidth = 1.0f;
button35.layer.borderColor = [[UIColor grayColor] CGColor];
Imagine how many lines of code were repeated and that to me does not mean a good thing, in this case would like to know how can I minimize it? it is possible to group all the buttons in one?
Upvotes: 1
Views: 2727
Reputation: 1738
Create a..
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *buttonCollection;
and connect all your buttons to this.
Then define your attributes in your user interface like this (screenshot is of my buttons, so set your properties how you wish)
Or cycle through your buttonCollection with this..put this in your viewDidLoad
for(UIButton *button in buttonCollection){
//capture frame
button.layer.borderWidth = 1.0f;
button.layer.borderColor = [[UIColor grayColor] CGColor];
}
Upvotes: 2
Reputation: 6932
This is possibly not the best way to do it but the idea is that a UIButton is inherits from a UIView.
So you can get your button Array by looking for the subviews of the view with the buttons on.
Use fast enumeration on the array to check the class is UIButton and make the changes.
NSArray * arr = _myView.subviews;
for (UIView * button in arr) {
NSLog(@" button %@", button);
if ([button isKindOfClass:[UIButton class]]) {
// UIButton* thisButton =button;
button.layer.borderWidth = 1.0f;
button.layer.borderColor = [[UIColor grayColor] CGColor];
}
}
My quick test does work here.
But as I say I cannot say if this is a good idea to do it this way,. Hopefully comments will educate me if there are pit falls..
Upvotes: 1
Reputation: 4111
for loop with array sample is some thing like this:
NSArray *keyPadImage=[[NSArray alloc]initWithObjects:@"keypad1-3.1.png",@"keypad2-3.1.png",@"keypad3-3.1.png",@"keypad4-3.1.png",@"keypad5-3.1.png",@"keypad6-3.1.png",@"keypad7-3.1.png",@"keypad8-3.1.png",@"keypad9-3.1.png",@"keypad-dot-3.1.png",@"keypad0-3.1.png",@"keypad-x-3.1.png",nil];
int height;
int count = [keyPadImage count];
for(int i=0;i<count;i++)
{
height=i/3;
UIButton *keyPad=[[UIButton alloc]initWithFrame:CGRectMake(15+(i%3)*92, 72+(height*75), 89, 72)];
[keyPad setBackgroundImage:[UIImage imageNamed:[keyPadImage objectAtIndex:i]] forState:UIControlStateNormal];
[keyPad addTarget:self action:@selector(modifyTotalAmount:) forControlEvents:UIControlEventTouchUpInside];
[keyPad setTag:(i+1)];
[self.view addSubview:keyPad];
}
Thanks
Upvotes: 0