簡體   English   中英

UILabel子類在Objective-C中顯示為UILabel

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM