Wednesday, December 17, 2014

UIButton with an image. Scale: aspect fit.

Updated with Xcode 8.0/Swift 3 (September 19, 2016): 


override func viewDidLoad() {
    super.viewDidLoad()
        
    let image = UIImage(named: "image.png")
    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
    button.imageView?.contentMode = UIViewContentMode.scaleAspectFit
    button.setImage(image, for: UIControlState.normal)
    button.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.touchUpInside)
    view.addSubview(button)
}
    
func buttonPressed() {
    print("button pressed!!")
}

Updated with Xcode 7.1.1/Swift 2.1 (November 12, 2015): 


    override func viewDidLoad() {
        super.viewDidLoad()
        
        let image = UIImage(named: "image.png")
        let button = UIButton(frame: CGRectMake(100, 100, 200, 200))
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        button.setImage(image, forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
    }
    
    func buttonPressed(sender: UIButton) {
        print("button pressed!!")
    }

Original post (December 17, 2014): 

   override func viewDidLoad() {
        super.viewDidLoad()
        
        let image = UIImage(named: "image.png") as UIImage!
        let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
        button.frame = CGRectMake(100, 100, 200, 200)
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        button.setImage(image, forState: .Normal)
        button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
    }

    func buttonPressed(sender: UIButton) {
        println("button pressed!!")
}

1 comment: