Ive added buttons to my view programmatically and i want to later on change their background color. The buttons 开发者_运维百科are of type custom. The following code has no effect.
for(UIView *v in [self.view subviews]){
if ([v isKindOfClass:[UIButton class]]){
//NSLog(@"View : %@", v);
[v setBackgroundColor:[UIColor redColor]];
}
}
Could some one please assist?
To paraphrase - you cannot change the color of UIButton (with UIButtonTypeRoundedRect). When you try changing it's background color you're rather changing the color of the rect the button is drawn on (which is usually clear). So there are two ways to go. Either you subclass UIButton and overwrite its -drawRect:
method or you create images for the different button states (which is perfectly fine to do).
If you are using IB to set background images you will notice that IB doesn't support setting images for all the states the button can have, so I recommend setting the images in code like so -
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
[button setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
[button setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];
The last line shows how to set an image for the selected & highlighted state (that's the one IB can't set). You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.
精彩评论