uibutton与图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uibutton与图像相关的知识,希望对你有一定的参考价值。

我有一个使用IB的按钮。现在我想以编程方式向按钮添加图像。如何设置按钮的图像尺寸大小,就像我们在IB布局 - >尺寸适合中一样。我想以编程方式进行

谢谢..

答案

您可以使用UIButtonsetImage:forState:方法将图像添加到按钮,然后使用UIViewcontentMode属性设置内容大小。

一个例子看起来像这样:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:@"myImage.png"];

button.frame = CGRectMake(20, 100, img.size.width, img.size.height);

[button setImage:img forState:UIControlStateNormal];
[button setImage:img forState:UIControlStateHighlighted];
[button setImage:img forState:UIControlStateSelected];

button.contentMode = UIViewContentModeScaleToFill; //Look up UIViewContentMode in the documentation for other options

[self.view addSubview:button];
另一答案
[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;

我想这可以帮到你

另一答案

示例代码,

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];
另一答案

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

以上是关于uibutton与图像的主要内容,如果未能解决你的问题,请参考以下文章

让 UIButton 图像的高度与 UIButton 文本标签的高度相同

uibutton与图像

如何使用代码为 UIButton 创建自定义图像?

在 UIImage 和 UIButton 的图像之间创建标识符

IOS SWIFT-基于uibutton图像的调用代码块

UIButton 上的 UIImage 模糊