[英]Custom UIView not visible on addSubview
我創建了一個簡單的ProgressView類,當我執行一些長任務時,希望顯示該類。 但是,當我將其添加到父視圖時,它永遠不會變得可見,也不會調用layoutSubviews。
該類的實現如下:
@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都不會顯示。
有人可以指出我正在犯的(很可能是愚蠢的)錯誤嗎?
您需要在-initWithTitle中而不是[super init]中調用指定的初始化程序:
self = [self initWithFrame: CGRectMake( 0, 0, 240, 112 )];
指定的初始化程序是調用超類的初始化程序的初始化程序,有關更多信息,請參見此處 。
好吧,我想通了,我真的很傻。
我正在使用導航控制器。 然后NavigtionViewController處理下載啟動。 唯一的問題是它是由子視圖控制器生成的。 所以我要將ProgressView添加到當前不可見的視圖中...
D'OH!
不好意思
我的新addSubview代碼如下:
[self.navigationController.topViewController.view addSubview: pProgressView];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.