[英]UILabel Subclass appears as UILabel in Objective-C
我是一位经验丰富的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;
在“界面生成器”中,选择标签,然后打开“身份检查器”。 在“类”文本字段中,它可能表示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可以正确解决)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.