【问题标题】:Setting UIImage as background of a UIButton将 UIImage 设置为 UIButton 的背景
【发布时间】:2012-02-24 04:04:56
【问题描述】:

以下代码有什么问题:

    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];

如果这是错误的,哪里需要纠正,为什么?

【问题讨论】:

  • 如果有错吗?你试过了吗?你应该知道它是否有效。
  • 在 IB 中这样做会容易得多。创建一个按钮,将类型设置为自定义,然后设置图像。您是否有理由需要以编程方式执行此操作?
  • 它对我有用。但有人告诉我UIImage *image = [[[UIImage alloc]init]autorelease]; image = [UIImage imageNamed:@"icon.png"]; 是错误的做法。
  • @Osiris 我的要求是以编程方式完成
  • @XaviValero 查看 dbrajkovic 和 Looyao 的答案。你还应该检查你的代码。

标签: iphone ios uibutton uiimage


【解决方案1】:

我看到了几个问题:

  1. 您将自动释放发送到映像,然后手动释放它。
  2. 您释放了按钮,但没有将其作为子视图添加到任何内容。所以基本上,你白白做了这一切。
  3. 实例化 UIImage,然后再次实例化它。在下一行: 而只是做: UIImage *image = [UIImage imageNamed:@"icon.png"]; 并删除UIImage *image = [[[UIImage alloc]init]autorelease]; 和[image release]; 语句。

【讨论】:

  • 你也应该看看下面 looyao 的回答!
【解决方案2】:

你可以试试这个

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"]; 这样,它将自动为 RetinaDisplay 加载 icon@2x(如果您将其添加到项目中)
【解决方案3】:

您确定image 不是nil?

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多