开发者

Change UIbuttons color after it has been created

开发者 https://www.devze.com 2023-04-04 20:05 出处:网络
I\'ve created a series of buttons and added them to the view, I was hoping to be able to access these buttons somehow and change th开发者_开发百科eir appearance.

I've created a series of buttons and added them to the view, I was hoping to be able to access these buttons somehow and change th开发者_开发百科eir appearance.

This is the two versions of code that i have tried, while I'm confident that it is locating the correct button nothing seems to happen to its background color.

  for(UIView *v in [self.view subviews]) {
        if ([v isKindOfClass:[UIButton class]]) {
            if (buttonTag == [v tag]) {
                v.backgroundColor = [UIColor redColor];
            }
        }
    }

and

 for (int i = 0; i < [[self.view subviews] count]; i++) {
        if ([[self.view.subviews objectAtIndex:i] class] == [UIButton class]) {
            NSLog(@"Tags : %i", [[self.view.subviews objectAtIndex:i] tag]);
            if (buttonTag == [[self.view.subviews objectAtIndex:i] tag]) {

                [[self.view.subviews objectAtIndex:i] setBackgroundColor:[UIColor redColor]];
            }
        }
    }

Thanks.


I can say that your first code version works for me, provided buttonTag's value is correct.

To debug, I suggest that you comment out the buttonTag comparison and just turn all your buttons red.

It may be that your button is not at the top level of your UIView hierarchy. It may be embedded in a subview. If so, you could put your loop into a recursive function.

Or, it may be that your UIButton backgroundColor is turned red, and you just can't see it. The interior of a rounded-rect button will remain white; only the areas outside the rounded corners will show red. A button with a background image might also cover any red.


You can use either:

  1. You can set selected property for example

    if(myButtton.selected = YES) { myButton.backgroundColor = [UIColor redColor]; } Also the highlighted properties are available as myBUtton.highlighted = YES;

OR

  1. You can set the background image or background color as follows: [myButton setBackgroundImage:[UIImage imagedNamed:strechableImage] forState:UIControlStateTouchUpInside];

    or for the normal state as: [myButton setBackgroundImage:[UIImage imagedNamed:strechableImage] forState:UIControlStateNormal];

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号