2012-04-04 50 views
6

我在這個網站上讀到如何嵌入和UILabel(子類UILabel並覆蓋所需的方法)。在將其添加到我的應用程序之前,我決定在獨立的測試應用程序中對其進行測試。代碼如下所示。SubClassing UILabel

這裏的MyUILabel.h

#import <UIKit/UIKit.h> 

@interface MyUILabel : UILabel 

@end 

這裏的MyUILabel.m

#import "MyUILabel.h" 
#import <QuartzCore/QuartzCore.h> 

@implementation MyUILabel 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 

// for border and rounding 
-(void) drawRect:(CGRect)rect 
{ 
    self.layer.cornerRadius = 4.0; 
    self.layer.borderWidth = 2; 

    [super drawRect:rect]; 
} 

// for inset 
-(void) drawTextInRect:(CGRect)rect 
{ 
    UIEdgeInsets insets = {0, 5, 0, 5}; 

    [super drawTextInRect: UIEdgeInsetsInsetRect(rect, insets)]; 
} 

這裏是我的ViewController.h

#import <UIKit/UIKit.h> 
#import "MyUILabel.h" 


@interface ViewController : UIViewController 
{ 
    MyUILabel *myDisplay; 
} 

@property (strong, nonatomic) IBOutlet MyUILabel *myDisplay; 

@end 

這裏的ViewController.m:

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

@synthesize myDisplay; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    myDisplay.text = @"Hello World!"; 
} 

- (void)viewDidUnload 
{ 
    [self setMyDisplay:nil]; 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 

@end 

的MyUILabel.m方法無(即林壓倒一切)被調用。

深入分析爲什麼非常感謝。

Regards,

拉蒙。

回答

5

好的。我做了一些進一步的挖掘,在Xcode中查看nib文件時可以看到一個字段。它是「身份檢查員」(左起第三個圖標)。這需要從UILabel更改爲MyUILabel。

現在它的工作!