改变子UIView背景颜色

时间:2013-03-07 04:33:57

标签: iphone ios6 xcode4.5 background-color

我正在尝试使用此方法在ViewController中添加子视图

- (void)viewDidLoad
{
    [super viewDidLoad];
    addCourse = [[UIView alloc]init];
    addCourse.backgroundColor = [UIColor redColor];
    [addCourse.layer setCornerRadius:50.0f];
    [addCourse.layer setMasksToBounds:YES];
}

addCoursesubview,但背景颜色仍为白色。我正在使用storyboard并添加了subview,并将视图与viewcontroller相关联,我确实编写了IBOutlet和属性并进行了合成,但仍然无法找到方法改变背景颜色。

我如何改变它?

4 个答案:

答案 0 :(得分:0)

您还没有像我看到的那样将addCourse添加到视图控制器中。将您的viewDidLoad方法替换为:

- (void)viewDidLoad
{
    [super viewDidLoad];
    addCourse = [[UIView alloc]init];
    addCourse.backgroundColor = [UIColor redColor];
    [addCourse.layer setCornerRadius:50.0f];
    [addCourse.layer setMasksToBounds:YES];
    //ADDED THIS LINE
    self.view = addCourse;
}

答案 1 :(得分:0)

试试这个:

addCourse = [[UIView alloc]initWithFrame:CGRectMake(x, y, w, h)];
addCourse.backgroundColor = [UIColor redColor];
[addCourse.layer setCornerRadius:50.0f];
[addCourse.layer setMasksToBounds:YES];

[self.view addSubview:addCourse];

它肯定会对你有所帮助。谢谢。

答案 2 :(得分:0)

如果您已经与ViewController链接,那么您只需要从代码中删除以下行

addCourse = [[UIView alloc]init];

因为它会创建子视图的新实例。

答案 3 :(得分:0)

请参阅我已更新您的代码(只需要设置视图的框架),我得到了结果

请!以这种方式更新您的代码

- (void)viewDidLoad
{
    [super viewDidLoad];

    //custom view
    UIView *addCourse = [[UIView alloc]init];
    CGRect myViewframe = CGRectMake(10.0f, 90.0f, 100.0f, 100.0f);
    addCourse.frame=myViewframe;
    addCourse.backgroundColor = [UIColor redColor];
    [addCourse.layer setCornerRadius:50.0f];
    [addCourse.layer setMasksToBounds:YES];

    [self.view addSubview:addCourse];
}

以下是结果屏幕

enter image description here

希望这对你有所帮助。