How To Set Swift Button Background Image Example

In previous article ( in this article’s reference section ), we have learnt how to create swift button with UIButton class and how to add click event process function to it, we have also known how to set swift button’s background color and how to create different type of swift button. In this article, i will tell you how to add image files into your Xcode project, and set the image files as the button’s background image.

1. Set Swift Button’s Background Image Example Demo.

In this example, there are one button located at the screen center, when it is in normal state, it will display a gray mac image, when you tap or click it to make the button highlighted, it will display a colorful mac image.

set swift button background image example

2. Create Set Swift Button Background Image Example Project Steps.

2.1 Add Images To Xcode Project.

  1. Create a Xcode swift project. Please refer How To Create A Swift Project In Xcode.
  2. Right click the project name, then click Add Files to “……” menu item in the popup menu list.add files to swift xcode project
  3. Select the images which you want to set as the button’s background image, after that you will see the images in the swift project left panel like below.
    set swift button backgroud images project file list

2.2 Load Above Image File In Swift Source Code Use UIImage Class.

UIKit.UIImage class is used to load Xcode swift project image files in swift source code. It provide two initializer function for you to use.

  1. UIImage(contentsOfFile: String) : This initializer function is used to load big size image file which is not saved in memory. The input parameter is the image file path. Below is example code.

    // First get the project image file path string. forResouce is the image file name, ofType is the  image file extension, do not include dot in ofType value.
    
    let imagePath:String? = Bundle.main.path(forResource: "gray mac image", ofType: "png")
    
    // Then create a UIImage object with above image file path string.        
    let image1:UIImage? = UIImage(contentsOfFile: imagePath!)
  2. UIImage(named: String) : This initializer function is used to load small size image file ( like icons ) and save the image file in memory for fast access. The parameter is the image file name with file extension.

    let image2:UIImage? = UIImage(named: "colorful mac image.png")

2.3 Set Button Background Image Use UIButton’s setBackgroundImage Function.

UIKit.UIButton class provide setBackgroundImage method for you to set an UIImage object as a button’s background image.

// Create a system default type UIButton object.
let btn1:UIButton = UIButton(type: UIButton.ButtonType.system)

// Set the button normal state background image.
btn1.setBackgroundImage(image1, for: UIControl.State.normal)

// Set the button highlighted state background image.
btn1.setBackgroundImage(image2, for: UIControl.State.highlighted)

3. Set Swift Button Background Image Example Source Code.

The only source file that need to be edited in this example is ViewController.swift file, below is this file’s source code.

//
//  ViewController.swift
//  SwiftSetButtonBackgroundImageExample
//
//  Created by song zhao on 7/11/19.
//  Copyright © 2019 dev2qa.com. All rights reserved.
//

import UIKit.UIImage

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Get screen width and height.
        let screenWidth = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        
        // Create a swift button.
        let btn1:UIButton = UIButton(type: UIButton.ButtonType.system)
        
        // Set the button location and size.
        btn1.frame = CGRect(x: 100, y: 100, width:100, height: 100)
        
        // Make the button locate at screen center.
        btn1.center = CGPoint(x: screenWidth/2, y: screenHeight/2)
        
        // Get the image file path. forResource is the image file name, ofType is the image file extension do not start with dot.
        let imagePath:String? = Bundle.main.path(forResource: "gray mac image", ofType: "png")
        
        // Get above image UIImage object.
        let imageNormal:UIImage? = UIImage(contentsOfFile: imagePath!)
        
        // Get another UIImage object.
        let imageHighlighted:UIImage? = UIImage(named: "colorful mac image.png")
        
        // Set background image for button normal state.
        btn1.setBackgroundImage(imageNormal, for: UIControl.State.normal)
        
        // Set background image for button highlighted state.
        btn1.setBackgroundImage(imageHighlighted, for: UIControl.State.highlighted)
        
        // Add the button in app screen.
        self.view.addSubview(btn1)
    }


}

References

  1. How To Create Multiple Button And Add Button Action Function Programmatically In iOS Swift
  2. How To Create Different Type Button Programmatically In Swift
  3. How To Use One IBAction For Multiple Buttons In Swift
READ :   How To Add iOS App Icon, Image, Color Set To Xcode Project Assets Catalog Correctly

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.