簡體   English   中英

子類化自定義UIView-如何初始化

[英]Subclassing a custom UIView - How to init

假設我有兩個視圖MyViewMySubview ,它們都是UIView子類。

View.h:

@interface MyView : UIView <ProgressCallback>
@property (retain, nonatomic) IBOutlet UIProgressBar *progress;

- (id) initWithFrame: (CGRect) frame;
- (void) progressUpdated: (NSNumber) newProgress;

@end

視圖

@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!
}

通過瀏覽Apple的文檔和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;
}

無論我如何初始化子類,都無法使進度條在子類中正常工作。 我可以在初始化期間設置它,但它不是nil,但顯然與初始化之后我認為的不匹配。 我認為這與我釋放自己的事實有關,但是如果我想返回View類型的類,則看不到任何其他選擇。 我使用相同的init樣式,只是將類名更改為Subview。 回調實際上已被調用並在代碼中進行了更改,但不會更新顯示。 一切都正確地連接在筆尖中,除了大小(在這種情況下,帶有圖像)之外,它們都是相同的。

(我盡力使示例代碼盡可能簡單明了。如果沒有成功,請告訴我,我將對其進行更新。)

您如何正確地繼承UIView? 我閱讀了文檔,沒有什么啟發性的,但是請隨時指出正確的方向。 具體來說,我必須重寫什么以使所有內容都指向正確的項目? 也就是說,那些在顯示器上。

initWithLabel:andWithFrame:方法中調用initWithFrame:之后,您將覆蓋self的值。

這行:

self = newView;

覆蓋在MyView超類init方法中創建的self的值,因此您將失去所有擁有的自定義

如果您也有這個問題,可能是因為我做錯了。

通常:

如果您對內容感到困惑,請重寫UIViewController

如果您搞砸了幾何,請重寫UIView

這解決了我的問題,盡管從技術上講我的代碼有問題的是wattson12所說的。

暫無
暫無

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

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