ios 将 UIImage 视图作为子视图添加到 UIView 的实例中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17557417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a UIImage View as a subView to an instance of UIView
提问by Danny Swan
I'm practicing beginner code since I'm new and I just have run into a whole lot of confusion here... this is what I have so far
因为我是新手,所以我正在练习初学者代码,我只是在这里遇到了很多困惑......这就是我到目前为止所拥有的
UIView *catView = [[UIView alloc] init];
UIImage *image = [UIImage imageNamed:@"lolcat.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[catView.view addSubview:imageView];
I don't understand what and why something in here is wrong, can someone help?
我不明白是什么以及为什么这里有问题,有人可以帮忙吗?
回答by soryngod
//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];
回答by snibbe
Interesting, and subtle note. If the views have already been added in an .xib file, the views are "weak" and you need to swap with a temp variable. Also some simple math to get the coordinates to match those that you set in your view:
有趣,微妙的音符。如果视图已添加到 .xib 文件中,则视图是“弱的”,您需要使用临时变量进行交换。还有一些简单的数学运算来获取坐标以匹配您在视图中设置的坐标:
@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;