UIButton with Background Image in Swift

The code snippet in this blog post demonstrates how to create a UIButton with a background image.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

To break it down in details, the following Swift code example will cover how to:

  • Create UIButton and position UIButton within a view,
  • Add UIButton as Subview,
  • Add target action to UIButton to call a local function when the button is tapped,
  • Create UIImage using a local image file added to the project,
  • Set UIButton background image.
import UIKit
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create image
        let image = UIImage(named: "no_image-128.png")
        
        let button = UIButton()
        button.frame = CGRect(x: 10, y: 100, width: 100, height: 100)
        button.setBackgroundImage(image, for: UIControl.State.normal)
        button.addTarget(self, action:#selector(self.imageButtonTapped(_:)), for: .touchUpInside)
        
        self.view.addSubview(button)
        
    }
    
    @objc func imageButtonTapped(_ sender:UIButton!)
    {
        print("My image button tapped")
    }
    
    
    override func didReceiveMemoryWarning() {
        
        super.didReceiveMemoryWarning()
        
    }
    
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published.