foreyez foreyez - 4 months ago 36
Swift Question

How to scale image and center it on a UIButton in Swift?

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)


I have an image that I've set on my button, but I'd like to scale it to be smaller than the button (for example the image should be 50,50) and center in the button. How might I do this in Swift?

Answer
var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png")
func buttonTouchDown(sender:UIButton!){
    println("button Touch Down")
}
override func viewDidLoad() {
    super.viewDidLoad()
    button.frame = CGRectMake(0,0 , 100, 100)
    button.backgroundColor = UIColor.clearColor()
    button.addTarget(self, action: "buttonTouchDown:", forControlEvents: .TouchDown)
    button.setImage(image, forState: .Normal)
    button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25)
    self.view.addSubview(button)
}
Comments