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

We have learned how to set a button background image in the article How To Set Swift Button Background Image Example. Besides this, you can also set an image as a swift button’s icon, and set an image as the 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.

  1. UIKit.UIButton class’s setImage method can set an icon image as a button icon. Please note the image format must be an icon format, otherwise, it will show the image incorrectly. Below is the swift example source code.
    // 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)
  2. If you also set the button title text, the text will be located at the icon image right side. The below picture is an example of a swift button with an image icon and text.
    set-swift-buttons-icon-image-
  3. If you do not use an icon format image, then you will see the below picture. The image will not be shown.
    set-button-icon-without-an-icon-format-image

2. Set Image As Button’s Background Color.

  1. Besides setting the button image icon, you can also set an image as the swift button’s background color.
  2. To do this, just create a UIColor object use a 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!)
  3. The below picture is the above code execution result, you can see that the image is displayed repeatedly at the button’s background in both directions, and the image size is not changed.
    set-image-as-swift-buttons-background-color-

3. Set Swift Button’s Background Image.

  1. The class UIKit.UIButton provides the setBackgroundImage method, this method can set the button’s background image for different button states. You can read the article How To Set Swift Button Background Image Example to learn more.
  2. Below is the example swift source code that uses the setBackgroundImage method.
    // 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)
  3. In this example, run the above source code will get the 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.
    set-swift-buttons-background-image

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

The above example demo video youtube URL is https://youtu.be/PICGaJzu33Y.

  1. There are three buttons in this example, the first button displays an icon with title text, the second button sets an image as its background color, the third button sets an image as its background.
  2. When the app starts, the third button partially covers 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.

5. Example Source Code.

  1. First, you should add the image files into your Xcode project, you can read the article How To Set Swift Button Background Image Example to learn more.
  2. Below is the example Xcode project source files list. We only need to edit the ViewController.swift file.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\IOSEXAMPLEPROJECT\SWIFTSETIMAGEASBUTTONICONBACKGROUNDCOLOREXAMPLE\SWIFTSETIMAGEASBUTTONICONBACKGROUNDCOLOREXAMPLE
    │   AppDelegate.swift
    │   color apple.png
    │   gray apple.jpeg
    │   icons8-apple-logo-96.png
    │   Info.plist
    │   ViewController.swift
    │
    ├───Assets.xcassets
    │   │   Contents.json
    │   │
    │   └───AppIcon.appiconset
    │           Contents.json
    │
    └───Base.lproj
            LaunchScreen.storyboard
            Main.storyboard
  3. You can refer to 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.
  4. ViewController.swift
    //
    //  ViewController.swift
    //  SwiftSetImageAsButtonIconBackgroundColorExample
    //
    //  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

1 thought on “How To Set An Image As Swift Button Icon, Background Color And Background Image Example”

  1. change background

    Someone wants to change background of their photo or cut out image. MasterLogix team make the best tool for <a href=”https://play.google.com/store/apps/details?id=com.logixgenetics.remover.background.image”>transparent background</a> & background remover in android app.

Leave a Comment

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.