2011-12-25 43 views
0

我有一個標籤,我想在少數地方使用它。它比下面的自定義設置UILabel上的自定義設置值得引入UILabel的子類

label.font = [UIFont fontWithName:@"Arial" size:12.0]; 
label.textAlignment = UITextAlignmentCenter; 
label.backgroundColor = [UIColor clearColor]; 
label.userInteractionEnabled = YES; 
label.textColor = [UIColor whiteColor]; 

現在我想知道而已,我需要引入(的UILabel)的一個子類,專門爲它?由於它在多個地方使用,這種用法的最佳設計模式是什麼?

回答

2

個人而言,我不會在這種情況下創建子類。有很多事情你可以做......你可以創建一個類別。例如在.H

@interface UILabel (MyLabel) 

+ (UILabel *)createMyLabelWithFrame; 

@end 

,並在.M:

@implementation UILabel (MyLabel) 

+ (UILabel *)createMyLabelWithFrame:(CGRect)frame { 
    UILabel *label = [[UILabel alloc] initWithFrame:frame]; 
    label.font = [UIFont fontWithName:@"Arial" size:12.0]; 
    label.textAlignment = UITextAlignmentCenter; 
    label.backgroundColor = [UIColor clearColor]; 
    label.userInteractionEnabled = YES; 
    label.textColor = [UIColor whiteColor]; 
    return label; 
} 
1

我會在某些可用的類上使用一個類或只是一個基本函數。子類創建更多的工作。即不斷必須改變IB中的班級或更改整個項目中的所有代碼。

範疇看起來是這樣的:

@implementation UILabel (FormatMyLabels) 
-(void)useMySpecialFormatting{ 
    self.font = [UIFont fontWithName:@"Arial" size:12.0]; 
    self.textAlignment = UITextAlignmentCenter; 
    self.backgroundColor = [UIColor clearColor]; 
    self.userInteractionEnabled = YES; 
    self.textColor = [UIColor whiteColor]; 
} 
@end 

而且你會用它想:

[self.myFirstLabel useMySpecialFormatting];

功能看起來是這樣的:

-(void)useSpecialFormattingOnLabel:(UILabel *)label{ 
    label.font = [UIFont fontWithName:@"Arial" size:12.0]; 
    label.textAlignment = UITextAlignmentCenter; 
    label.backgroundColor = [UIColor clearColor]; 
    label.userInteractionEnabled = YES; 
    label.textColor = [UIColor whiteColor]; 
} 

你就可以使用這就像:

[ClassOrInstanceWithFunction useSpecialFormattingOnLabel:self.myFirstLabel];