Iphone 将UIImage设置为UIButton的背景
以下代码有什么问题:Iphone 将UIImage设置为UIButton的背景,iphone,ios,uibutton,uiimage,Iphone,Ios,Uibutton,Uiimage,以下代码有什么问题: 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
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 imagename:@“icon.png”]代码>
并删除UIImage*image=[[[UIImage alloc]init]autorelease]
和[图像发布]代码>语句李>
你可以试试这个
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
如果错了呢?你试过了吗?您应该知道它是否工作。在IB中执行此操作要容易得多。创建一个按钮,将类型设置为“自定义”,然后设置图像。你有什么理由需要以编程的方式来做这件事吗?这对我很有用。但是有人告诉我,UIImage*image=[[UIImage alloc]init]autorelease];image=[UIImage ImageName:@“icon.png”]
是一种错误的方法。@Osiris我的要求是这样做programmatically@XaviValero查看dbrajkovic和Looyao的答案。你也应该检查你的代码。很好。我错过了第一行!还有一件事。去掉.png文件<代码>UIImage*图像=[UIImage ImageName:@“icon”]代码>这样,它将自动加载icon@2x(如果您将其添加到项目中)对于RetinaDisplay,您还应该查看下面looyao的答案!