How can I set a button background color on iPhone?

后端 未结 18 2029
予麋鹿
予麋鹿 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 20:50

    So, I found an incredibly simple solution using categories. (So simple that I think I must be doing something hacky, but I don't see it!)

    Define a category (if you don't know what that is, in summary: it is a way to "extend" a class minimally; that is, to add methods to a class but no properties) for UIButton, and create a method "setBackgroundColor" that calls UIButton's super class' (UIControl) setBackgroundColor method.

    @implementation UIButton (coloredBackgroundButton)
    
    -(void)setBackgroundColor:(UIColor *)backgroundColor {
        [super setBackgroundColor:backgroundColor];
    }
    

    Wherever you use UIButtons, as long as you import the header file in which this category is declared, in this case,

    #import "coloredBackgroundButton.h" 
    

    you can call setBackgroundColor on them.

提交回复
热议问题