因此,假設我有兩個視圖,MyView
和MySubview
,這兩個視圖的子類都是UIView
。子類定製UIView - 如何初始化
View.h:
@interface MyView : UIView <ProgressCallback>
@property (retain, nonatomic) IBOutlet UIProgressBar *progress;
- (id) initWithFrame: (CGRect) frame;
- (void) progressUpdated: (NSNumber) newProgress;
@end
View.m
@implementation MyView
@synthesize progress = _progress;
- (id)initWithFrame:(CGRect)frame;
{
self = [super initWithFrame:frame];
if (self){
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"MyViewNibFile"
owner:nil
options:nil];
if ([arrayOfViews count] < 1){
[self release];
return nil;
}
View *newView = [[arrayOfViews objectAtIndex:0] retain];
[newView setFrame:frame];
[self release];
self = newView;
self.progress.progress = .25 // This will work and change it.
}
return self;
}
- (void) progressUpdated: (NSNumber) newProgress {
self.progress.progress = newProgress.floatValue; // This also works!
}
我發現通過瀏覽蘋果的文檔和StackOverflow上創建的UIView的子類的這個方法。它的工作原理,我可以根據回調來設置我的進度,它會出現,等等。我的問題是當我想子視圖。
MySubview.h
@interface MySubview : MyView
@property (retain, nonatomic) IBOutlet UIImageView *image;
@end
MySubview.m
@implementation MySubview
- (id)initWithLabel: (UIImageView *) image andWithFrame:(CGRect)frame;
{
self = [super initWithFrame:frame];
if (self){
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"MySubViewNibFile"
owner:nil
options:nil];
if ([arrayOfViews count] < 1){
[self release];
return nil;
}
MySubbiew *newView = [[arrayOfViews objectAtIndex:0] retain];
[newView setFrame:frame];
[self release];
self = newView;
self.progress.progress = .25 // This will work and change it.
self.image = image; // Also works
}
return self;
}
無論我如何初始化我的子類,我不能讓進度條在子類工作。我可以在init中設置它,但它不是零,但它顯然不對應於init後的視圖中的那個。我認爲這與我釋放自己的事實有關,但是如果我想返回一個類型爲View的類,則看不到其他選擇。我使用相同樣式的init,只是將類名更改爲Subview。回調實際上被調用並且在代碼中改變,但它不更新顯示。所有東西都正確地連接在筆尖上,除了尺寸以外,它們是相同的,在這種情況下,它們與圖像相同。
(我儘量使示例代碼簡單,並儘可能清楚。如果我沒有成功,請讓我知道,我會更新它。)
你如何正確子類的UIView ?我閱讀了文檔,沒有任何證據可以啓發,但請隨時指出我的方向。具體而言,我必須重寫什麼才能讓所有內容指向正確的項目?也就是顯示器上的那些。
可可觸摸與可可不一樣,所以這個問題不應該相應地編輯。 – 2012-08-12 13:26:53
self = newView;這不會破壞繼承。如果您以後想要子類MySubview,您的初始化程序將returen MySubview類而不是您要創建的新類。 – 2016-03-09 11:28:14