简体   繁体   English

将UIImage设置为UIButton的背景

[英]Setting UIImage as background of a UIButton

Whats wrong with the following piece of code: 以下代码段有什么问题:

    UIButton *button = [[UIButton alloc]init];
    CGRect frame = CGRectMake(180, 10, 33, 33);
    button.frame = frame;
    button.tag = 1001;
    UIImage *image = [[[UIImage alloc]init]autorelease];
    image = [UIImage imageNamed:@"icon.png"];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [image release];
    [button release];

If this is wrong where does it need correction and why? 如果这是错误的,则在哪里需要更正?为什么?

I see several problems: 我看到几个问题:

  1. You sent autorelease to image, then manually released it. 您已将自动释放发送到映像,然后手动释放了它。
  2. You released button, but you didn't add it as a subview to anything. 您释放了按钮,但没有将其添加为任何子视图。 So basically, you did all that for nothing. 因此,基本上,您一无所有。
  3. You instantiate UIImage, then you do instantiate it again. 您实例化UIImage,然后再次实例化它。 in the next line: Instead just do: UIImage *image = [UIImage imageNamed:@"icon.png"]; 在下一行中:而是执行以下操作: UIImage *image = [UIImage imageNamed:@"icon.png"]; and delete UIImage *image = [[[UIImage alloc]init]autorelease]; 并删除UIImage *image = [[[UIImage alloc]init]autorelease]; and [image release]; [image release]; statement. 声明。

You can try this 你可以试试这个

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(180, 10, 33, 33);;
button.tag = 1001;
UIImage *image = [UIImage imageNamed:@"icon.png"];
if (image == nil) {
    NSLog(@"can't find icon.png");
} else {
    [button setBackgroundImage:image forState:UIControlStateNormal];
}
//add button to the parent's view

您确定image不是nil吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM