2011-08-16 139 views
3

我试图从是从厦门国际银行加载自定义视图类的.m内做到这一点,而是编程:UIView的背景颜色的设置自

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

    self.backgroundColor=[UIColor redcolor]; 
} 
return self; 
} 

我有无论我把背景颜色放在initWithFrame还是其他方法中都是一样的结果。背景颜色属性不需要。从控制器,拥有该自定义视图,我可以设置背景色精,有:

self.mycustomview.backgroundColor=[UIColor redcolor]; 

但我想从自定义视图自身内做到这一点,保持这样的东西无关。控制器和自定义视图导入UIKit。

我也试过这个,这是可以从代码预见:

self.View.backgroundColor=[UIColor redcolor]; 

但这并不工作。我在这里尝试了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]; 

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

#import <UIKit/UIKit.h> 

@interface mapButtons : UIView 
+0

当我编译我得到这个错误“请求成员的backgroundColor东西不是一个结构或联合” – johnbakers

回答

2

我再次测试,这是我在做什么完整的源代码该工程

// MapButtons.h 
#import <UIKit/UIKit.h> 

// As a note you normally define class names starting with a capital letter 
// but I did test this with mapButtons as you had it 
@interface MapButtons : UIView 

@end 

// MapButtons.m 
#import "mapButtons.h" 

@implementation mapButtons 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     self.backgroundColor = [UIColor redColor]; 
    } 
    return self; 
} 

@end 

// TestAppDelegate.m 
@implementation TestAppDelegate 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    MapButtons *view = [[MapButtons alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

    [self.window addSubview:view]; 

    [self.window makeKeyAndVisible]; 
    return YES; 
} 

是Xcode不是自动完成为奇数的事实,但我似乎所以我没有真正解决这个问题的间歇。人们有时会建议删除项目派生数据并重新启动xcode。

+0

嗯..一定有别的事情上。当我键入它时,XCode甚至不完成“backgroundcolor”;尽管它会在拥有此功能的视图控制器中执行此操作。你在MyView.h/m的顶部导入了什么? – johnbakers

+0

您的自定义视图是否扩展了'UIView'?例如'@interface MyView:UIView' –

+0

我给我的问题添加了一条评论,我得到的错误是 – johnbakers

5

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

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

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

    return self; 
} 
+0

谢谢,但我以编程方式添加视图,不涉及XIB。我会更新这个问题来反映这一点。 – johnbakers

+0

我为我的问题添加了一条评论,提供了错误信息 – johnbakers