为什么addSubview不显示?

时间:2012-08-30 10:47:50

标签: objective-c ios

我想以编程方式将myView添加到父视图中。但它没有出现在屏幕上。代码有什么问题?

@interface ViewController ()
@property (nonatomic,weak) UIView *myView;
@end

@implementation ViewController
@synthesize myView = _myView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect viewRect = CGRectMake(10, 10, 100, 100);
    self.myView = [[UIView alloc] initWithFrame:viewRect];
    self.myView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.myView];
}

2 个答案:

答案 0 :(得分:7)

替换

@property (nonatomic,weak) UIView *myView;

@property (strong, nonatomic) UIView *myView;

它应该工作:)

答案 1 :(得分:2)

@interface ViewController ()

@end

@implementation ViewController

UIView *myView;

-(void)viewDidLoad
{
    [super viewDidLoad];

    CGRect viewRect = CGRectMake(10, 10, 100, 100);

    myView = [[UIView alloc] initWithFrame:viewRect];

    myView.backgroundColor = [UIColor redColor];

    [self.view addSubview:myView];
}

尝试一下它会起作用......

相关问题