代码之家  ›  专栏  ›  技术社区  ›  Joshua

创建自定义ui按钮

  •  3
  • Joshua  · 技术社区  · 16 年前

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

    4 回复  |  直到 14 年前
        1
  •  15
  •   Nick Forge    16 年前

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

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

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

    [myButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    

    当您将背景图像设置为 UIButton 对于 UIControlStateNormal ,它作为 全部的 状态,除非为任何其他状态显式设置不同的背景图像。

        2
  •  1
  •   Rolf Hendriks    15 年前

    更好的是,使用uiview的contentStretch属性。否则,如果使用LeftCapWidth的可伸缩图像缩小图形或使用灯光或光泽度效果拉伸复杂图形,可能会遇到一些令人不快的意外。

        3
  •  0
  •   Klaus Busse    14 年前

    嗯,uiview的contentStretch属性是正确的解决方案,但不幸的是,它不适用于uibutton background属性(至少xcode 4.0.2)。它甚至在ib中被公开,所以您不需要任何代码。

        4
  •  -4
  •   Thomas Kekeisen    16 年前

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

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