How To Set Swift Button Background Image Example

In the previous article ( in this article’s reference section ), we have learned how to create a swift button with UIButton class and how to add click event process function to it, we have also known how to set the swift button’s background color and how to create a 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 file as the button’s background image.

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

If you can not see the above demo video, you can access the youtube URL https://youtu.be/bQ9X1pWdXrw to see it.

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

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

2.1 Add Images To Xcode Project.

  1. Create an Xcode swift project. Please refer to 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.
  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.

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

  1. UIKit.UIImage class is used to load Xcode swift project image files in Swift source code. It provides two initializer function for you to use.
  2. 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 the 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!)
  3. UIImage(named: String): This initializer function is used to load small size image files ( like icons ) and save the image file in memory for fast access. The parameter is the image file name with a file extension.

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

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

  1. UIKit.UIButton class provides 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.

  1. 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
    //
    //  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
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x