Krish
Krish

Reputation: 4242

How to make Custom UILabel in ios

In my project there is huge number of UIlabels. I have created one separate custom class for UILabel and I have set all label's properties in that class.

Here my main requirement is some labels' color is white and some labels' text color is black but color is not applying.

CustomUILabel class:-

#import "CustomLabel.h"

@implementation CustomLabel

-(void)layoutSubviews{

    [self setupUI];
}

- (void)setupUI {

    [self setTextAlignment:NSTextAlignmentLeft];
    [self setFont:[UIFont fontWithName:@"Futura" size:14.0]];
    [self setBackgroundColor:[UIColor clearColor]];
    [self setTextColor:[UIColor blackColor]];
}

@end

Main class:-

#import "MainViewController.h"

@interface MainViewController (){

}

@end

@implementation MainViewController
@synthesize label1,label2;


- (void)viewDidLoad {
    [super viewDidLoad];

     label1.textColor = [UIColor whiteColor];
     label2.textColor = [UIColor blackColor];
}

Upvotes: 0

Views: 1649

Answers (2)

rob mayoff
rob mayoff

Reputation: 385500

When you override layoutSubviews, you must call [super layoutSubviews]. But that's not your problem here. The problem is that you're calling setupUI in layoutSubviews, and you shouldn't. Layout happens after viewDidLoad, so your attempt to set the color in viewDidLoad gets overridden later during layout, when setupUI runs.

You should be calling setupUI from the init methods of your subclass:

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setupUI];
    }
    return self;
}

And you shouldn't override layoutSubviews at all in CustomLabel.

Upvotes: 3

rmaddy
rmaddy

Reputation: 318774

The problem is with your layoutSubview method and your setupUI method.

layoutSubviews is not the proper place to call setupUI. layoutSubviews can be called many times and is most likely being called a couple of times after viewDidLoad is called which is why the colors are being reset back to black.

And always call [super layoutSubviews]; in your layoutSubviews method.

The better place to call your setupUI method is from one or more of the appropriate init... methods and possibly awakeFromNib.

Upvotes: 2

Related Questions