SubClassing UILabel

Pha*_*m59 6 subclass uilabel

我在同一个网站上读到了如何插入和UILabel(子类UILabel并覆盖所需的方法).在将它添加到我的应用程序之前,我决定在一个独立的测试应用程序中测试它.代码如下所示.

这是MyUILabel.h

#import <UIKit/UIKit.h>

@interface MyUILabel : UILabel

@end
Run Code Online (Sandbox Code Playgroud)

这是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)];
}
Run Code Online (Sandbox Code Playgroud)

这是我的ViewController.h

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


@interface ViewController : UIViewController
{
    MyUILabel   *myDisplay;
}

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

@end
Run Code Online (Sandbox Code Playgroud)

这是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
Run Code Online (Sandbox Code Playgroud)

MyUILabel.m(我重写)中没有任何方法被调用.

深入了解为什么非常感谢.

问候,

拉蒙.

Pha*_*m59 5

好.我做了一些进一步的挖掘,在Xcode中,在查看nib文件时可以看到一个字段.它是'Identity Inspector'(左起第3个图标).这需要从UILabel更改为MyUILabel.

现在它有效!