UILabel子类在Objective-C中显示为UILabel



我是一名经验丰富的C++程序员,试图创建UILabel的第一个Objective-C子类,并添加只读属性

// UINumericlabel.h
@interface UINumericLabel : UILabel
// Returns true if the numeric display contains a decimal point
@property (readonly,nonatomic) BOOL hasDecimalPoint;
@end

//  UINumericLabel.m
#import "UINumericLabel.h"
@implementation UINumericLabel
// Returns true if the numeric display contains a decimal point
- (BOOL) hasDecimalPoint;
{
   return [self.text rangeOfString:(@".")].location != NSNotFound;
}
@end

当我试图引用实例化的UINumericLabel的hasDecimalPoint属性时,我得到了一个中止,并出现错误 2012-02-20 18:25:56.289 Calculator[10380:207] -[UILabel hasDecimalPoint]: unrecognized选择器发送到实例0x684c5c0

在调试器中,它显示了我将UINumericLabel属性声明为UILabel*我需要重写UINumericLabel子类中UILabel的(id)init吗?我该怎么做?

#import "UINumericLabel.h"
@interface CalculatorViewController : UIViewController <ADBannerViewDelegate>
@property (weak, nonatomic) IBOutlet UINumericLabel *display0;
@end

当我将鼠标悬停在调试器中的display0P上时,它显示它是UILabel*而不是UINumericLabel*

UINumericLabel*display0P=self.display0;

在Interface Builder中选择标签,然后打开Identity Inspector。在文本字段"Class"中,它可能显示UILabel。将其更改为新的子类UINumericLabel

我同意上面的@Brian,但要添加两件事:(1)除非您计划缓存BOOL值,否则不需要声明的属性。只需使用一个在.h中有预先声明的方法,(2)在这种情况下不需要子类。一个更好的方法是扩展,比如:UILabel+JonN.h…

@interface UILabel (JonN)
-(BOOL)hasDecimal;
@end

然后,在UILabel+JonN.m…

@implementation UILabel (JonN)
// your method as written
@end

我认为,这更漂亮,解决了你在IB方面遇到的问题(我认为@Brian正确地解决了这个问题)。

最新更新