2014-02-18 59 views
2

我創建了一個簡單的ProgressView類,當我執行一些長期任務時,我想顯示它。但是,當我將它添加到父視圖中時,它永遠不可見,並且layoutSubviews永遠不會被調用。自定義UIView在addSubview上不可見

類實現如下:

@implementation ProgressView 

@synthesize title; 
@synthesize cancel; 
@synthesize progress; 
@synthesize delegate; 

- (id)initWithFrame:(CGRect)frame 
{ 
    //frame = CGRectMake(0, 0, 240, 112); 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     self.title  = [[UILabel alloc] init]; 
     self.cancel  = [UIButton buttonWithType: UIButtonTypeCustom]; 
     self.progress = [[UIProgressView alloc] init]; 

     self.backgroundColor = [UIColor darkGrayColor]; 

     [self addSubview: self.title]; 
     [self addSubview: self.cancel]; 
     [self addSubview: self.progress]; 
    } 
    return self; 
} 

+ (id) createWithTitle: (NSString*) pTitle 
{ 
    ProgressView* pRet = [[ProgressView alloc] initWithTitle: pTitle]; 
    return pRet; 
} 

- (id) initWithTitle: (NSString*) pTitle 
{ 
    self = [super initWithFrame: CGRectMake(0, 0, 240, 112)]; 
    if (self) 
    { 
     self.title.text = pTitle; 
    } 
    return self; 
} 

- (void) layoutSubviews 
{ 
    CGSize superFrameSize  = self.superview.frame.size; 
    CGSize halfSuperFrameSize = CGSizeMake(superFrameSize.width/2, superFrameSize.height/2); 

    CGSize frameSize   = self.frame.size; 
    CGSize halfFrameSize  = CGSizeMake(frameSize.width/2, frameSize.height/2); 

    // Center the window on its parent. 
    [self setFrame: CGRectMake(halfSuperFrameSize.width - halfFrameSize.width, halfSuperFrameSize.height - halfFrameSize.height, frameSize.width, frameSize.height)]; 

    [self.title  setFrame: CGRectMake(4, 4, frameSize.width - 8, 24)]; 
    [self.progress setFrame: CGRectMake(4, 32, frameSize.width - 8, 24)]; 
    [self.cancel setFrame: CGRectMake(4, 64, frameSize.width - 8, 44)]; 

    [self setNeedsDisplay]; 
} 

我加的觀點如下:

pProgressView = [[ProgressView alloc] initWithTitle: @"Downloading..."]; 
[pProgressView setDelegate: self]; 
[self.view addSubview: pProgressView]; 

但它永遠不會顯示。我已經檢查過移除是肯定會發生的,並且有足夠的時間讓視圖變得可見。然而,我不知所措。無論我做什麼,ProgressView都不會顯示。

有人能指出我犯的錯誤,最可能是愚蠢的錯誤嗎?

+0

你在哪裏添加您的看法?這個問題可能來自這裏 –

+0

@NicolasBonnet:謝謝尼古拉斯,但我認爲我不會奇怪地做任何事情。我正在做一個委託調用,我已經確認這是在主線程中發生的。 – Goz

+0

我也確認了幾秒鐘後,當下載完成時,pProgressView.superview與s「self.view」是一樣的... – Goz

回答

0

好吧,我想到了,我真的很愚蠢。

我正在使用導航控制器。 NavigtionViewController處理下載啓動。唯一的問題是它由子視圖控制器生成。因此,我將ProgressView添加到當前不可見的視圖中...

D'OH!

對不起所有。

我的新addSubview代碼如下:

[self.navigationController.topViewController.view addSubview: pProgressView]; 
3

你需要調用指定的初始化中-initWithTitle,不是[超級初始化]:

self = [self initWithFrame: CGRectMake(0, 0, 240, 112)]; 

指定初始化是調用父類的初始化,請參閱here更多信息的人。

+0

這不起作用... – Goz

+1

只是爲了澄清這是在你的'initWithTitle' – Flexicoder

+0

但唉,它不幫幫我。仍然沒有顯示... – Goz