我在这里找到了很多解决方案,但不是Swift,我知道你可以使用UIImageView做到这一点,但在我的情况下,我需要以编程方式为UIButton设置alpha透明背景图像.最好的是UIImage扩展!
let img = UIImage(named: "imageWithoutAlpha")
var imgInsets = UIEdgeInsetsMake(0, 24, 0, 24)
image = image!.resizableImageWithCapInsets(imgInsets)
let myButton = UIButton(frame: CGRect(x: 50, y: 50, width: img!.size.width, height: img!.size.height))
myButton.setBackgroundImage(img, forState: UIControlState.Normal)
myButton.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 20)
myButton.setTitle("Startbutton", forState: UIControlState.Normal)
myButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
myButton.sizeToFit()
view.addSubview(myButton)
Run Code Online (Sandbox Code Playgroud)
目前的结果:

期望的结果:
