Objective C: Programmatically create a UIImageView

天涯浪子 提交于 2019-12-07 08:46:05

问题


I'm trying to make a UIImageView with a .png load up in the location of a button when it is clicked.

brickAnim = UIImageView.alloc;           ///////freezes during runtime
[brickAnim initWithFrame:currentBrick.frame];
[brickAnim setImage:[NSString stringWithFormat:@"brick-1.png"]];
[self.view addSubview:brickAnim];

current brick is the name of the button that's being clicked. I've narrowed it down and figured out that the first line causes the app to freeze and exit. I can't figure out what I'm doing wrong.


回答1:


try

brickAnim = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"brick-1.png"]];
brickAnim.frame = currentBrick.frame;
[self.view addSubview:brickAnim];

edit after seeing response to other answer:

are you declaring and initializing brickAnim elsewhere? if not, you need to add at the beginning:

UIImageView *brickAnim = [[UIImageView alloc] ....;

and at the end:

[brickAnim release];



回答2:


You need to create a UIImage first, since setImage wants an UIImage object. Something like this may work (note that this is a class method):

[brickAnim setImage:[UIImage imageNamed:@"brick-1.png"]];

Look at the UIImage reference, i'm not sure this will work (since imageNamed may want a different path-format).



来源:https://stackoverflow.com/questions/4671253/objective-c-programmatically-create-a-uiimageview

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