How can I set a button background color on iPhone?

后端 未结 18 2099
予麋鹿
予麋鹿 2020-11-30 20:22

How can I set a custom background color of a button?

Interface Builder doesn\'t seem to have an interface to do this.

Is it only available programmatically

18条回答
  •  余生分开走
    2020-11-30 21:07

    I read your question to require (as I do) a programmatic way to set button color. It's a glaring omission from the UIKit, and I couldn't get the undocumented UIGlassButton to work.

    I've solved this with a single segment UISegmentedControl, which allows you to set the tintColor:

    UISegmentedControl * btn = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:name]];
    btn.momentary = YES;
    btn.segmentedControlStyle = UISegmentedControlStyleBar;
    btn.tintColor = color;
    [btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
    

    Note please that the momentary and segmentedControlStyle properties do matter, and that an image can be used instead of a NSString * name.

    A stretchable image with end caps works fine if you can use a finite set of canned images, but that doesn't fit the requirement! E.g.,

    buttonImage   = [[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:26 topCapHeight:16];
    

提交回复
热议问题