uibutton与图像

时间:2011-04-25 06:03:04

标签: iphone uibutton

我正在使用IB按钮。现在我想以编程方式向按钮添加图像。如何像在IB布局中那样设置按钮的图像尺寸大小 - >尺寸适合。我想以编程方式执行此操作

谢谢..

4 个答案:

答案 0 :(得分:9)

您可以使用UIButton的{​​{1}}方法将图像添加到按钮,然后使用setImage:forState:的{​​{1}}属性设置内容大小。

示例如下:

UIView

答案 1 :(得分:3)

[yourButton setImage:yourImage forState:UIControlStateNormal];
yourButton.contentMode = UIViewContentModeScaleToFill;

contentMode的值可以是以下任何一个

typedef enum {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
} UIViewContentMode;

我认为这可以帮到你

答案 2 :(得分:2)

示例代码,

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img1 = [UIImage imageNamed:@"image1.png"];
btn.frame = CGRectMake(20.0 , 270.0, img1.size.width, img1.size.height);
[btn setImage:img1 forState:UIControlStateNormal]; 
UIImage *img2 = [UIImage imageNamed:@"image2.png"];
[btn setImage:img2 forState:UIControlStateHighlighted];
[btn setImage:img2 forState:UIControlStateSelected];
[btn addTarget:self action:@selector(Action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

答案 3 :(得分:1)

使用UIButton的 sizeToFit 方法(实际上是UIView)。