How to add system icons for a UIButton programmatically?

import UIKit

extension UIImage {

    public convenience init?(_ systemItem: UIBarButtonItem.SystemItem) {

        guard let sysImage = UIImage.imageFrom(systemItem: systemItem)?.cgImage else {
            return nil
        }

        self.init(cgImage: sysImage)
    }

    private class func imageFrom(systemItem: UIBarButtonItem.SystemItem) -> UIImage? {

        let sysBarButtonItem = UIBarButtonItem(barButtonSystemItem: systemItem, target: nil, action: nil)

        //MARK:- Adding barButton into tool bar and rendering it.
        let toolBar = UIToolbar()
        toolBar.setItems([sysBarButtonItem], animated: false)
        toolBar.snapshotView(afterScreenUpdates: true)

        if  let buttonView = sysBarButtonItem.value(forKey: "view") as? UIView{
            for subView in buttonView.subviews {
                if subView is UIButton {
                    let button = subView as! UIButton
                    let image = button.imageView!.image!
                    return image
                }
            }
        }
        return nil
    }
}

This is an example of how do we use it:

 let button = UIButton() ;
 let systemImage = UIImage(systemItem: .trash) ;
 button.setImage(systemImage, for: .normal)

For Swift 5 the syntax is:

button.setImage(UIImage(systemName: "search"), for: .normal)

You can also set the weight of the icon by adding SymbolConfiguration:

let boldConfig = UIImage.SymbolConfiguration(weight: .bold)
let boldSearch = UIImage(systemName: "search", withConfiguration: boldConfig)

button.setImage(boldSearch, for: .normal)

See: Apple documentation for available names (API column) or go to Interface Builder, select UIButton and in the Attributes Inspector select Image which will give you list of all available icons.

Interface Builder icons


I found 2521 system icons, as numerated values.

@available(iOS 13.0, *)
@objc public extension UIImage{

    var assetName: String? {
        guard let imageAsset = imageAsset else { return nil }
        return imageAsset.value(forKey:"assetName") as? String
    }

    static var square_and_arrow_up: UIImage? {
        return UIImage(systemName: "square.and.arrow.up")
    }
    static var square_and_arrow_up_fill: UIImage? {
        return UIImage(systemName: "square.and.arrow.up.fill")
    }
    static var square_and_arrow_down: UIImage? {
        return UIImage(systemName: "square.and.arrow.down")
    }
    ...

screenshot: screenshot github: link


Now you can just do

button.setImage(UIImage(.search), for: .normal)