繁体   English   中英

自定义UIView在addSubview上不可见

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM