开发者

What is the correct way to re-use UILabel's style?

I have several UILabels which have same visual treatment. Instead of redefining every single property every time, I am thinking of just making copies of an instance 开发者_如何转开发and changing the text. Is this how it should be done?

Another way is to create a factory method, but I'm not that fond of the idea.


If you're willing to learn Three20, you could use the TTLabel class, which is incorporated with Three20's stylesheet system, which is basically designed to solve your problem. However, I personally have had trouble parsing Three20's so-called documentation, so I think learning to use this library just to solve your problem is a lot of overhead.

My work-around for this problem is to put together a mini factory method, like this:

// Example:
- (UILabel *)makeLabel {
  UILabel *label = [[[UILabel alloc] init] autorelease];
  label.backgroundColor = [UIColor clearColor];
  label.font = [UIFont systemFontOfSize:kMyFontSize];
  label.textColor = [UIColor blueColor];
  label.textAlignment = UITextAlignmentCenter;
  [self.view addSubview:label];
  return label;
}

Then when I use this method, other code gets cleaner:

UILabel *nameLabel = [self makeLabel];
nameLabel.text = userName;
UILabel *titleLabel = [self makeLabel];
titleLable.text = myTitle;
// Both labels have consistent style.

PengOne suggests subclassing UILabel. That's an option, although I think this factory method does the job just as well with less work.


It seems like you want to subclass UILabel so that it defaults to your preferences. It's pretty simple to do. Create a new file in Xcode (and Objective C Class) called CustomLabel (or whatever you like).

CustomLabel.m :

#import <UIKit/UIKit.h>

@interface CustomLabel : UILabel {
}

@end

CustomLabel.h :

#import "CustomLabel.h"

@implementation CustomLabel

- (id)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        // CUSTOMIZATION HERE
    }
    return self;
}

- (void)dealloc {
    [super dealloc];
} 

@end

If this seems like overkill, then you can just create a method in your ViewController to do the customization:

-(void)customizeLabel:(UILabel *)label {
    // CUSTOMIZATION HERE
}

then call this on any label you create.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜