我有一个使用 IB 的按钮。现在我想以编程方式将图像添加到按钮。如何设置按钮的图像大小,就像我们在 IB Layout -> Size to Fit 中所做的那样。我想以编程方式完成
谢谢..
最佳答案
您可以使用 UIButton
的 setImage: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/