2011-09-20 114 views
0

我创建了基于视图的应用程序。 我有一个sampleGameViewContrioller.xib,其中包含主视图和子视图,它们与类行为相关联。如何将UIImageView添加到UIView(而不是UIViewController)?

SampleViewController.xib:

  • 查看
    • 查看< - 行为

在sampleViewContoller.m我创建类行为的实例:

Behavior *b = [[Behavior alloc] initilizeWithType:@"type" position:rect mapArray:arrMap]; 

Behavior.m:

-(id) initilizeWithType:(NSString *)type position:(CGRect) pos mapArray:(NSMutableArray *) mapArr { 

self = [super initWithFrame:CGRectMake(0, 0, 1024, 570)]; 
if (self != nil) { 
if ([type isEqualToString:@"type"]) { 
arrMap = mapArr; 
self.rectForDraw = pos; 
self.file = [[NSString alloc]initWithString:@"girl.png"]; 
UIImageView *imgg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"girl.png"]]; 
imgg.frame = rect; 
[self addSubview:imgg]; 
timer = [NSTimer scheduledTimerWithTimeInterval:0.015 target:self selector:@selector(moving:) userInfo:nil repeats:YES]; 
} 
} 
return self;} 

但它不起作用。图像不会添加到我的视图中。

,如果我加入的ImageView - (空)的drawRect:(的CGRect)RECT,它的工作:

- (void)drawRect:(CGRect)rect { 
self.img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"girl.png"]]; 
self.img.frame = CGRectMake(100, 100, 100, 100); 
[self addSubview:self.img]; } 

但我要送通过构造函数类的行为绘制的参数。如何添加imageView而不使用方法drawRect,使用我的构造函数?

对不起我的英文:)

+0

你可以澄清以下内容:在你的视图控制器中创建它后,你用'b'做什么?你最近的代码片段中重写了哪个'drawRect'?这是行为类吗? – jrturton

+0

我创建了一个类的实例来管理它们中的每一个。类绘制图像并将其移动到自己的逻辑中。 因此,创建了一个实例数组,其中每个实例负责移动图像。 – Benjamin

+0

>>您最近的代码片段中重写了哪个drawRect?这是行为类吗? 是的,在Behavior类中。但它只是一个示例 – Benjamin

回答

1

如果妳希望通过简单的UIView添加的形象图,然后就去做[self.view addSubview:imageview];如果你正在从行为类方法图像,然后从该方法返回的UIImageView和它添加到您的看法 试试这个:

Behavior *b = [[Behavior alloc] init]; 

在行为类然后写一个方法

-(UIImageView*) initilizeWithType:(NSString *)type position:(CGRect) pos mapArray:(NSMutableArray *) mapArr { 
// Your Logic 

return imgView; //UIImageView object 
} 

然后在您的视图控制器调用此方法

UIImageView *imgView=[b initilizeWithType:@"YOUR STRING" position:YOUR RECT pos mapArray:YOUR ARRAY ]; 
+0

它不起作用。 – Benjamin

+0

消息:在'行为*'类型的对象上找不到“属性'视图' – Benjamin

+0

使行为成为UIView的子类。或者U可以将方法的返回类型(在Behavior中)设置为UIImageView,或者只是执行'[self addSubView:imageView]' – iosfanboy9

0
imgg.frame = rect; 

这条线,据我可以看到你的分配框架的ImageView对什么都没有。这应该是pos还是rectForDraw?当在drawRect中添加到视图中时,您明确地设置了一个真实框架,因此这可能是差异所在。

+0

我有错误。我写它的例子。 即使我写'imgg.frame = CGRectmake(100,100,100,100)',图像也不会出现。 – Benjamin

相关问题