Apple Interface Builder: adding subview to UIImageView

烈酒焚心 提交于 2019-12-27 17:02:53

问题


I created UIImageView with the help of Interface Bulder. Now I want to place label inside it (as its subview). In code I can type something like: [myUIImageView addSubview:myUILabel]; But can I do it with the help of IB? I found the solution for UIView, but can't find something similar for UIImageView.


回答1:


You cannot add a subview to UIImageView in interface builder for reasons only known to Apple! You are right in saying that you can addSubview programmatically, but then, the overhead of setting autoresizing masks and placements of subviews should all be handled in code, which is cumbersome.

So there is an easy workaround. Instead of dragging an instance of UIImageView in the nib, just drag a UIView and change its class to UIImageView from UIView (cmd+4 option of inspector). The only difference you find in the nib for default imageView instance and your new UIImageView subclass instance is: you cannot set image to your new imageView from nib (cmd+1 option). So, in the -viewDidLoad method of its appropriate viewController, set image to this outlet of UIImageView.

By doing so, you are free to add subviews to your "now UIImageView" instances in interface builder, which is much easy.

Hope this helps . . .




回答2:


I would like to add answer.

While it sucks you cannot add subview to UIImageView, you can get the same effect by incorporating UIView with transparent (clear color) background.

Then put the UIImageview BEFORE it.

So the UIView has the subviews and the UIImageview is the background of the UIView.

I think that's apple's intent.

Here is a screenshot:

Here is the result:

Don't forget to set background as clear color

Now if someone could actually point me to a tutorial how to do this it'll be great. I spent hours doing it the checked answered way. The checked answer is a fine answer but very unintuitive because you can't see your background image clearly while working. I think mine is the proper way to do so.




回答3:


In latest XCode(4.5) there is an option to drag and drop the required controls to the parent.

It is quite easy. Attached screen shot for the same. I dragged the Label/TextField and Button to UIImageView




回答4:


Use this code:

UIImage *image = [UIImage imageNamed:@"background.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view insertSubview:imageView atIndex:0];

(replace background.png with image) (replace atIndex:0 with whatever place in the .index root you want to insert the image and your off.



来源:https://stackoverflow.com/questions/2415561/apple-interface-builder-adding-subview-to-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!