设置的UIImage作为一个UIButton
的背景哪些错误与下面的代码段:设置的UIImage作为一个UIButton
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];
如果这是错误的地方它需要修正,为什么?
我看到几个问题:
- 您发送自动释放图像,然后手动释放它。
- 您发布了按钮,但您并未将其作为子视图添加到任何内容中。所以基本上,你做了所有这些。
- 你实例化UIImage,然后你再次实例化它。在下一行:取而代之的是:
UIImage *image = [UIImage imageNamed:@"icon.png"];
并删除UIImage *image = [[[UIImage alloc]init]autorelease];
和[image release];
声明。
你还应该看看looyao的答案! – dbrajkovic 2012-02-24 04:22:03
您是否确定image
不是nil
?
你可以试试这个
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
呼叫良好。我错过了第一行!还有一件事。摆脱.png。 'UIImage * image = [UIImage imageNamed:@“icon”];'这样,它会自动加载图标@ 2x(如果您将它添加到您的项目中)RetinaDisplay – dbrajkovic 2012-02-24 04:19:01
这很好@looyao – Kamarshad 2012-02-24 05:17:57
** **如果它是错的?你试过了吗?你应该知道它是否工作。 – smitec 2012-02-24 04:07:01
在IB中这样做会容易得多。创建一个按钮,将类型设置为自定义,然后设置图像。是否有需要以编程方式执行此操作的原因? – Osiris 2012-02-24 04:08:50
它为我工作。但我被告知'UIImage * image = [[[UIImage alloc] init] autorelease]; image = [UIImage imageNamed:@“icon.png”];'是一个错误的方法。 – 2012-02-24 04:09:01