iPhone : How to set BackgroundColor of UIButton with buttonType UIButtonTypeCustom

前端 未结 15 1461
有刺的猬
有刺的猬 2020-12-01 13:45

i want to change the button color when it is clicked. I used :

[button setBackgroundColor:[UIColor redColor]];

but this shows red color onl

15条回答
  •  生来不讨喜
    2020-12-01 14:29

    Make sure the button type is custom as someone else already stated. Then doing the following will bring back those rounded corners:

     [self.myButton.layer setCornerRadius:8.0f];
     [self.myButton.layer setMasksToBounds:YES];
     [self.myButton.layer setBorderWidth:1.0f];
     [self.myButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
     self.myButton.backgroundColor = [UIColor redColor];
    

    Though, personally, I'm a big fan of gradient buttons over solid colors... also, background color doesn't have different states, whereas background images do:

     [self.myButton setBackgroundImage:[UIImage imageNamed:@"gradient.png"] forState:UIControlStateNormal];
    

    Using an image, your button will darken with selection (or you could provide a different background image per state to do something different). This won't happen with background color, the background will always stay the same, only your button label changing per state.

提交回复
热议问题