我正在尝试使用 swift 以编程方式设置按钮的样式
let acButton = UIButton.buttonWithType(.Custom) as! UIButton
acButton.frame = CGRectMake(0, 0, buttonWidth, buttonHeight)
acButton.setImage(UIImage(named: "ac"), forState: .Normal)
acButton.imageEdgeInsets = UIEdgeInsetsMake(10,10,10,10)
acButton.layer.borderWidth = 1
acButton.layer.borderColor = UIColor.grayColor().CGColor
acButton.addTarget(self, action: "acPressed", forControlEvents: .TouchUpInside)
self.view.addSubview(acButton)
但我在 iPad Air 等大屏幕设备上遇到了一些小问题(见图片)图像不适合按钮框架,我也尝试将图像设置为按钮的背景图像但我没有得到我想要的想要因为imageEdgeInsets似乎不适用于backgroundImage。
解决方案:
使用imageWithCGImage:scale:orientation
获取图像,如下方法:
func getScaledImage(img: UIImage, btn: UIButton) -> UIImage {
// Check which dimension (width or height) to pay respect to and
// calculate the scale factor
var imgRatio: CGFloat = img.size.width / img.size.height
var btnRatio = btn.frame.size.width / btn.frame.size.height
var scaleFactor = (imgRatio > btnRatio) ? img.size.width / btn.frame.size.width : img.size.height / btn.frame.size.height
// Create image using scale factor
var scaledImg = UIImage(CGImage: img.CGImage, scale: scaleFactor, orientation: UIImageOrientation.Up)
return scaledImg!
}
为了实现这一点,我们会这样写:
let acImage = getScaledImage(UIImage(named: "ac")!, btn: acButton)
acButton.setImage(acImage, forState: .Normal)
这里是最终代码:
let acButton = UIButton.buttonWithType(.Custom) as! UIButton
acButton.frame = CGRectMake(0, 0, buttonWidth, buttonHeight)
let acImage = getScaledImage(UIImage(named: "ac")!, btn: acButton)
acButton.setImage(acImage, forState: .Normal)
acButton.imageEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20)
acButton.addTarget(self, action: "acPressed", forControlEvents: .TouchUpInside)
basicCalculatorView.addSubview(acButton)
最佳答案
您尝试过添加约束吗?那应该可以很好地扩展它。
关于ios - Swift - 以编程方式在大屏幕上显示 UIButton 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078465/