设置UIView背景颜色的自我

joh*_*ers 3 objective-c uiview

我试图从没有从XIB加载的自定义视图类的.m内部执行此操作,而是以编程方式执行此操作:

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code

    self.backgroundColor=[UIColor redcolor];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)

我是否将背景颜色放在initWithFrame或其他方法中,我有相同的结果.背景颜色属性不需要.从拥有此自定义视图的控制器,我可以设置背景颜色,使用:

self.mycustomview.backgroundColor=[UIColor redcolor];
Run Code Online (Sandbox Code Playgroud)

但是我想在自定义视图中做到这一点,保持这样的东西独立.控制器和自定义视图导入UIKit.

我也试过这个,可以从Code Sense获得:

    self.View.backgroundColor=[UIColor redcolor];
Run Code Online (Sandbox Code Playgroud)

但这也不起作用.我试过这里viewView这里.我敢肯定我忽视了一些非常明显的事情.

在视图控制器中我有这个,它工作正常.自定义视图称为"mapButtons.h":

- (void)viewDidLoad
{
CGRect frame=CGRectMake(0, 0, 320, 460);
self.mapButtons=[[mapButtons alloc] initWithFrame:frame];
self.mapButtons.backgroundColor=[UIColor redColor];

[self.view addSubview:self.mapButtons];
Run Code Online (Sandbox Code Playgroud)

自定义视图的.h是这样的:

#import <UIKit/UIKit.h>

@interface mapButtons : UIView
Run Code Online (Sandbox Code Playgroud)

Noa*_*oon 5

如果您的视图是从XIB创建的(即您使用Interface Builder将其添加到其他视图中),-initWithFrame:则不会被调用.-initWithCoder:而是从XIB加载的对象接收.试试这个:

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];

    if(self)
    {
        self.backgroundColor = [UIColor redColor];
    }

    return self;
}
Run Code Online (Sandbox Code Playgroud)