uilabel - 子类化 UILabel

标签 uilabel subclass

我在同一个站点中阅读了如何插入和 UILabel(子类 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 中的任何方法(我覆盖的)都没有被调用。

非常感谢深入了解原因。

问候,

拉蒙。

最佳答案

好的。我做了一些进一步的挖掘,在 Xcode 中查看 nib 文件时有一个字段可见。它是“身份检查员”(左起第三个图标)。这需要从 UILabel 更改为 MyUILabel。

现在它起作用了!

关于uilabel - 子类化 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10004466/

相关文章:

ios - 在 UIView 中将标签居中

ios - sizeToFit() 返回错误的高度 - 需要在 heightForRow 中找到单元格宽度

objective-c - UILabel带有标签,无法设置文本

ios - 标签文本不会改变,但 View 接收变量

c++ - 在自身内部定义类的标准实例 (C++)

ios - Swift - 枚举的子类(或类似的东西)

ios - 如何管理文本字形边界

python - Python 类和子类

C# :base class work when defining the subclass? 怎么办

c# - 使用 IoC 将依赖项注入(inject)基类和子类?