2012-04-04 30 views
6

Tôi đọc trong cùng trang web này cách chèn và UILabel (lớp con UILabel và ghi đè lên các phương thức được yêu cầu). Trước khi thêm nó vào ứng dụng của tôi, tôi quyết định thử nghiệm nó trong một ứng dụng thử nghiệm độc lập. Mã được hiển thị bên dưới.SubClassing UILabel

Dưới đây là MyUILabel.h

#import <UIKit/UIKit.h> 

@interface MyUILabel : UILabel 

@end 

Dưới đây là 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)]; 
} 

Dưới đây là ViewController.h tôi

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


@interface ViewController : UIViewController 
{ 
    MyUILabel *myDisplay; 
} 

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

@end 

Dưới đây là 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 

Không ai trong số các phương pháp trong MyUILabel.m (mà Im trọng) được gọi.

Thông tin chi tiết về lý do được đánh giá cao.

Kính trọng,

Ramon.

Trả lời

5

Ok. Tôi đã làm một số đào sâu hơn và trong Xcode có một lĩnh vực có thể nhìn thấy khi nhìn vào tập tin nib. Nó là 'Identity Inspector' (biểu tượng thứ 3 từ bên trái). Điều này cần phải được thay đổi từ UILabel thành MyUILabel.

Bây giờ nó hoạt động!