将UIImage视图作为子视图添加到UIView的实例

时间:2013-07-09 20:19:21

标签: ios objective-c uiimageview addsubview

我正在练习初学者代码,因为我是新手,我在这里遇到了很多困惑......这就是我到目前为止所拥有的

UIView *catView = [[UIView alloc] init];
UIImage *image = [UIImage imageNamed:@"lolcat.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[catView.view addSubview:imageView];

我不明白为什么这里有什么东西是错的,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:28)

//You need to specify the frame of the view   
UIView *catView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,400)];

UIImage *image = [UIImage imageNamed:@"lolcat.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

//specify the frame of the imageView in the superview , here it will fill the superview
imageView.frame = catView.bounds;

// add the imageview to the superview
[catView addSubview:imageView];

//add the view to the main view

[self.view addSubview:catView];

答案 1 :(得分:0)

有趣且细微的音符。如果视图已经添加到.xib文件中,那么视图就会“弱”。你需要与temp变量交换。还有一些简单的数学运算可以使坐标与您在视图中设置的坐标相匹配:

@property (weak, nonatomic) IBOutlet UIImageView *imageView1;
@property (weak, nonatomic) IBOutlet UIImageView *imageView2;
CGRect tempFrame; 

tempFrame = self.imageView1.frame;

CGRect tempFrame;   // use bounds instead

tempFrame = self.imageView2.frame;

__strong UIImageView * tempView = self.imageView2;
[self.imageView2 willMoveToSuperview: nil];
[self.imageView2 removeFromSuperview];
[self.imageView2 willMoveToSuperview: self.imageView1];
[self.imageViewSkate addSubview: self.imageViewBall];
self.imageView2.frame = CGRectMake(tempFrame.origin.x - self.imageView1.frame.origin.x,
                                      tempFrame.origin.y - self.imageView1.frame.origin.y,
                                      tempFrame.size.width, tempFrame.size.height);
tempView = nil;