Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling UIButtons - subclass?

I have four buttons that are going to be styled in the same way on the same scene (using Storyboard). This is simple styling that will require overriding a few of the property defaults, but seems needlessly repetitive to set this for each individual button. I was thinking I’d create a subclass, but a lot of the posts I’ve read (particularly on stackoverflow) warn against doing this for UIButton (and the attempts I’ve made haven’t been successful).

Just hoping to get a general pointer on what’s considered the best approach for this. Thanks for any advice.

like image 439
resedasue Avatar asked Dec 27 '22 05:12

resedasue


1 Answers

If you are targeting only iOS 5, I strongly recommend watching Session 114 - Customizing the Appearance of UIKit Controlsdeveloper login required of the WWDC 2011 Session Videos.

It explains in detail App-wide styling.


I want to modify yujis idea: Use a category on UIButton to setup the button

.h.

@interface UIButton (MyStyling)
-(void)configureMyButtonStyle;
//other methods for more fine-grained control
@end

.m

@implementation UIButton (MyStyling)
-(void)configureMyButtonStyle
{
    [self setBackgroundColor:[UIColor colorWithRed:…]];
    [self setTitleColor: [UIColor colorWithRed:…] forState: UIControlStateNormal];
    //…

}
@end

Now you can call [aButton configureMyButtonStyle]

Of course you can also parse in some parameters, to distinguish several style.

-(void)configureMyButtonForStyle:(NSInteger)style
{
    if(style == 1){
        //…
    } else if(style == 2) {
       //..
    } else {
       //fallback style 
    }
}

use:

[aButton configureMyButtonForStyle:1];
like image 187
vikingosegundo Avatar answered Dec 29 '22 19:12

vikingosegundo