How To Set An Image As Swift Button Icon, Background Color And Background Image Example

We have learnt how to set a button background image in article How To Set Swift Button Background Image Example. Besides this, you can also set an image as swift button’s icon, and set an image as swift button background color. This article will show you how to do it and the difference between them.

1. Set Icon Image As Swift Button’s Icon.

UIKit.UIButton class’s setImage method can set an icon image as button icon. Please note the image format must be an icon format, otherwise it will show the image incorrectly.

// Load an icon format image to a UIImage object.
let iconImage:UIImage? = UIImage(named: "icons8-apple-logo-96.png")
......
        
// Set above UIImage object as button icon.
iconBtn.setImage(iconImage, for: UIControl.State.normal)

If you also set button title text, the text will be located at the icon image right side. Below picture is an example of swift button with icon and text.

set swift button's icon image

If you do not use icon format image, then you will see below picture. The image will not be shown.

set button icon without an icon format image

2. Set Image As Button’s Background Color.

Besides set button image icon, you can also set image as swift button’s background color. To do this, just create a UIColor object use selected UIImage object, then set the UIColor object as the button’s backgroundColor property value. Please see below example source code.

// Create a UIImage object use image, the image file format is not limited. 
let backgroundColorImage:UIImage? = UIImage(named: "gray apple.jpeg")  
......
// Clear the button background color.
imageAsBackgroundColorBtn.backgroundColor = UIColor.clear
......  
// Create a UIColor object with above UIImage object, and set it as the button's backgroundColor.
imageAsBackgroundColorBtn.backgroundColor = UIColor(patternImage: backgroundColorImage!)

Below picture is above code execution result, you can see that the image is displayed repeatedly at button’s background in both direction, and the image size is not changed.

set image as swift button's background color

3. Set Swift Button’s Background Image.

UIKit.UIButton class provide setBackgroundImage method, this method can set button’s background image for different button state. You can read article How To Set Swift Button Background Image Example to learn more.

// Load an jpeg image.
let backgroundImage:UIImage? = UIImage(named: "gray apple.jpeg")
......
// Set above UIImage object as the button's background image for normal button state.
backgroundImageBtn.setBackgroundImage(backgroundImage, for: UIControl.State.normal)

In this example, run above source code will get below picture. You can see that the image is not repeatedly displayed, only one image is shown, but the image size is changed to full fill the button’s size.

READ :   How To Create Different Type Button Programmatically In Swift

set swift button's background image

4. Set Image As Button’s Icon, Background Color And Background Image Example.

There are three buttons in this example, the first button display an icon with title text, the second button set image as it’s background color, the third button set an image as it’s background.

When the app start, the third button partially cover the second button, but when you click the second or the third button, it will bring the clicked button to the front of the screen.

set image as swift button icon, background color, background image example

5. Example Source Code.

First you should add the image files into your Xcode project, you can read article How To Set Swift Button Background Image Example to learn more.

Below is the example Xcode project source files list. We only need to edit ViewController.swift file. You can refer articles How To Create A Swift Project In Xcode to learn Xcode project creation,  How To Create Multiple Button And Add Button Action Function Programmatically In iOS Swift to learn how to process button click event programmatically in source code.

set image as button icon, background color and background image example project files list

ViewController.swift

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

import UIKit

class ViewController: UIViewController {
    
    // Get the screen width an height.
    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    
    // This button will show you how to set an icon image for a button, the image should be an icon type.
    let iconBtn:UIButton = UIButton(type: UIButton.ButtonType.system)
    
    // This button will show you how to set an image as a swift button background color.
    let imageAsBackgroundColorBtn:UIButton = UIButton(type: UIButton.ButtonType.custom)
    
    // This button will show you how to set an image as a button's background image.
    let backgroundImageBtn:UIButton = UIButton(type: UIButton.ButtonType.custom)

    // Define button tag values constant variable.
    let TAG_IMAGE_AS_BACKGROUND_COLOR_BTN = 1
    let TAG_BACKGROUND_IMAGE_BTN = 2
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setButtonIconImage()
        
        setImageAsButtonBackgroundColor()
        
        setButtonBackgroundImage()

    }

    /* This function will load an icon image and set it as a button's icon. The icon locate at button left side, while the button title locate at button right side. */
    func setButtonIconImage() -> Void{
        
        let iconImage:UIImage? = UIImage(named: "icons8-apple-logo-96.png")
        
        let iconImageHeight = iconImage?.size.height
        
        iconBtn.setTitle("Button Icon Image", for: UIControl.State.normal)
        
        iconBtn.frame = CGRect(x: 10, y: 10, width: 2*screenWidth/3, height: iconImageHeight!)
        
        iconBtn.backgroundColor = UIColor.clear
        
        iconBtn.setImage(iconImage, for: UIControl.State.normal)
        
        iconBtn.setTitleColor(UIColor.red, for: UIControl.State.normal)
        
        iconBtn.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/5)
        
        iconBtn.layer.borderColor = UIColor.green.cgColor
        
        iconBtn.layer.borderWidth = 2
        
        self.view.addSubview(iconBtn)
    }
    
    /* This function will use an image as a button's background color. It will not stretch the image, it will keep the image size as original, and repeat display same image on both direction. */
    func setImageAsButtonBackgroundColor() -> Void{
        
        let backgroundColorImage:UIImage? = UIImage(named: "gray apple.jpeg")
        
        imageAsBackgroundColorBtn.setTitle("Image As Button Background Color", for: UIControl.State.normal)
        
        let backgroundImageSize:CGSize = backgroundColorImage!.size
        
        imageAsBackgroundColorBtn.frame = CGRect(x: 10, y: 10, width: 1.5 * backgroundImageSize.width, height: 1.5*backgroundImageSize.height)
        
        imageAsBackgroundColorBtn.backgroundColor = UIColor.clear
        
        imageAsBackgroundColorBtn.backgroundColor = UIColor(patternImage: backgroundColorImage!)
        
        imageAsBackgroundColorBtn.setTitleColor(UIColor.red, for: UIControl.State.normal)
        
        imageAsBackgroundColorBtn.center = CGPoint(x: screenWidth/2, y: screenHeight/2)
        
        imageAsBackgroundColorBtn.layer.borderColor = UIColor.green.cgColor
        
        imageAsBackgroundColorBtn.layer.cornerRadius = 15
        
        imageAsBackgroundColorBtn.layer.borderWidth = 2
        
        // Set tag attribute for this button, the tag attribute value is used to identify the button uniquely.
        imageAsBackgroundColorBtn.tag = TAG_IMAGE_AS_BACKGROUND_COLOR_BTN
        
        // Register function to process this button's on click event.
        imageAsBackgroundColorBtn.addTarget(self, action: #selector(changeButtonOrder), for: UIControl.Event.touchUpInside)
        
        self.view.addSubview(imageAsBackgroundColorBtn)
    }
    
    /* This function will set an image as the button's background image, it will stretch the image to fill the button size. So the image size is changed, and there is only one image in the background. */
    func setButtonBackgroundImage() -> Void{
        
        let backgroundImage:UIImage? = UIImage(named: "gray apple.jpeg")
        
        backgroundImageBtn.setTitle("Image As Button Background", for: UIControl.State.normal)
        
        let backgroundImageSize:CGSize = backgroundImage!.size
        
        backgroundImageBtn.frame = CGRect(x: 10, y: 10, width: 1.5 * backgroundImageSize.width, height: 1.5*backgroundImageSize.height)
        
        backgroundImageBtn.backgroundColor = UIColor.clear
        
        backgroundImageBtn.setBackgroundImage(backgroundImage, for: UIControl.State.normal)
        
        backgroundImageBtn.setTitleColor(UIColor.red, for: UIControl.State.normal)
        
        backgroundImageBtn.center = CGPoint(x: screenWidth/2, y: 2 * screenHeight/3)
        
        backgroundImageBtn.layer.borderColor = UIColor.green.cgColor
        
        backgroundImageBtn.layer.borderWidth = 2
        
        // Set tag attribute for this button, the tag attribute value is used to identify the button uniquely.
        backgroundImageBtn.tag = TAG_BACKGROUND_IMAGE_BTN
        
        // Register function to process this button's on click event.
        backgroundImageBtn.addTarget(self, action: #selector(changeButtonOrder), for: UIControl.Event.touchUpInside)
        
        self.view.addSubview(backgroundImageBtn)
        
    }
    
    /* This function is invoked when the second and third button is clicked.*/
    @objc func changeButtonOrder(src: UIButton) -> Void{
        
        // Use the button tag attribute value to identify which button is clicked.
        if(src.tag == TAG_IMAGE_AS_BACKGROUND_COLOR_BTN){
            
            // Bring the button to the screen front.
            self.view.bringSubviewToFront(imageAsBackgroundColorBtn)
            
        }else if(src.tag == TAG_BACKGROUND_IMAGE_BTN){
            
            self.view.bringSubviewToFront(backgroundImageBtn)
            
        }
        
    }

}

References

  1. How To Make Rounded Border Button In Swift

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.