首页 文章

为什么addSubview不显示?

提问于
浏览
2

我想以编程方式将 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 回答

  • 7

    更换

    @property (nonatomic,weak) UIView *myView;
    

    @property (strong, nonatomic) UIView *myView;
    

    它应该工作:)

  • 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];
    }
    

    试试这个会起作用......

相关问题