簡體   English   中英

未在drawRect方法中設置屬性-iOS

[英]Property not set in drawRect method - iOS

當我嘗試訪問我的drawRect方法中的類變量或屬性時,我一直看到一些奇怪的行為。

在我的.h文件中,我有以下內容

@interface DartBoard : UIView
{
    Board * board;
    int index;
}
@property (readwrite, assign, nonatomic) NSNumber * selectedIndex;
@end

在我的.m文件中,我具有以下內容

@implementation DartBoard

@synthesize selectedIndex;

-(id)init
{
    self.selectedIndex = [NSNumber numberWithInt:5];
    index = 123;
    return self;
}

- (void)drawRect:(CGRect)rect {
    NSLog(@"selectedIndex: %d",[self.selectedIndex intValue]);
    NSLog(@"index: %d",index);
}

@end

輸出是

2012-06-12 19:48:42.579 App [3690:707] selectedIndex: 0
2012-06-12 19:48:42.580 App [3690:707] index: 0

我一直在尋找解決方案,但是沒有運氣。

我發現了類似的問題,但沒有真正的答案

參見: UIView drawRect; 類變量超出范圍

我感覺drawRect與普通方法不同,無法正確獲取類的范圍,但是如何解決?

干杯達米安

我覺得drawRect與普通方法不同,並且無法正確獲取類的范圍

不, -drawRect:沒有什么特別的。

有兩種可能性:

1.您的-init方法沒有被調用。

您沒有說明如何創建此視圖-是手動調用[[DartBoard alloc] init]還是從nib文件取消存檔。

如果它來自筆尖,則UIView的取消存檔不知道應該調用您的init方法。 它將改為調用指定的初始值設定項 ,即-initWithFrame:

因此,您應該改為實現該方法,並確保調用super!

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.selectedIndex = [NSNumber numberWithInt:5];
        index = 123;
    }
    return self;
}

2.您的視圖可能有兩個實例:一個是您手動init ,另一個是來自其他地方(可能是筆尖)的。 第二個實例是正在繪制的實例。 由於從未設置其變量和屬性,因此它們顯示為零(默認值)。

您可以將此行添加到-init-drawRect:方法中,以查看self的值是什么。 (或者,使用調試器進行檢查。)

NSLog(@"self is %p", self);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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