【问题标题】:Creating a Custom UIButton创建自定义 UIButton
【发布时间】:2010-04-25 11:10:59
【问题描述】:

我希望以编程方式创建一个自定义 UIButton(不是子类),我希望它有一个随着 UIButton 宽度的增加而拉伸的背景图像。我该怎么做?

【问题讨论】:

    标签: cocoa-touch uikit uibutton


    【解决方案1】:

    首先创建一个可拉伸的UIImage(假设按钮图像末尾的“cap”为10px):

    UIImage *backgroundImage = [[UIImage imageNamed:@"ImageBackground.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    

    然后使用可拉伸的图片作为背景:

    [myButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    

    当您在 UIButton 上为 UIControlStateNormal 设置 backgroundImage 时,它​​将充当 所有 状态的背景,除非您为任何其他状态显式设置不同的 backgroundImage。 p>

    【讨论】:

    • 我知道这是如何工作的,但由于某种原因,我正在使用的代码 (gist.github.com/378341) 没有向视图添加任何内容。我的 redButton.png 文件在我的资源中。
    • 检查(使用调试器或使用NSLog)您的backgroundImage 不为零。如果+[UIImage imageNamed:] 找不到你的图片,它会返回 nil。
    • 次要 nit:-stretchableImage… 接受 2 个整数作为输入,而不是浮点数。
    • @Nick 我已经像这样设置了一个 NSLog:` NSLog(@"background: %d", backgroundImage);` 它会打印出background: 0
    • @KennyTM:感谢您发现这一点。编辑修复。 @Joshua:在这种情况下,由于某种原因UIImage 找不到您的图像。确保具有该 exact 名称(区分大小写)的图像在您的 Xcode 项目中,而不仅仅是在 Xcode 项目的文件夹中。要将图像添加到项目中,请将其从 Finder 拖到项目窗口中。
    【解决方案2】:

    更好的是,使用 UIView 的 contentStretch 属性。否则,如果您使用 stretchableImageWithLeftCapWidth 来缩小图形或拉伸具有光照或光泽效果的复杂图形,您可能会得到一些令人讨厌的惊喜。

    【讨论】:

      【解决方案3】:

      好吧,UIView 的 contentStretch 属性将是正确的解决方案,但不幸的是它不适用于 UIButton 背景属性(至少 XCode 4.0.2)。它甚至在 IB 中公开,因此您不需要任何代码。

      【讨论】:

        【解决方案4】:

        您必须将使用“stretchableImageWithLeftCapWidth:topCapHeight:”方法创建的 UIImage 设置为按钮背景。例如:

        UIImage *yourBackgroundImage = [[UIImage imageNamed:@"yourImage.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
        yourButton.backgroundColor = [UIColor colorWithPatternImage:yourBackgroundImage];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-05
          • 2014-11-03
          • 1970-01-01
          • 1970-01-01
          • 2021-04-22
          • 1970-01-01
          相关资源
          最近更新 更多