2012-04-04 49 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。

现在它的工作!