iphone - 带图像的 uibutton

标签 iphone uibutton

我有一个使用 IB 的按钮。现在我想以编程方式将图像添加到按钮。如何设置按钮的图像大小,就像我们在 IB Layout -> Size to Fit 中所做的那样。我想以编程方式完成

谢谢..

最佳答案

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

示例如下所示:

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

关于iphone - 带图像的 uibutton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5775687/

相关文章:

iphone - 为什么 [response expectedContentLength] 总是返回 -1

ios - Swift:如何通过按住按钮逐步调整 UIView 的大小

swift - 在 Swift 中进行应用内购买时,隐藏不同 View Controller 中的 UIButton

ios - 触摸移动 UIButton

iphone - 单击时如何使自定义按钮键像iPhone按钮键一样大

ios - 如何使 UIButton 悬垂在父 View 上并仍然使其全部可选?

iphone - UITableView 编辑模式不工作

iphone - OpenCV iOS 阻止 Crash

iphone - UIScrollview 垂直和水平滚动 ios

ios - 执行 segue 时哪个对象是发送者?