Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the size of an SF icon in a UIButton

Tags:

icons

uibutton

Very simple question here. I'd like to change the size of an SF icon in a UIButton. I've tried doing this 20 ways to Wednesday.

  1. I tried setting the EdgeInsets - no dice
  2. I tried resetting the contentMode of the button's imageView - doesn't budge
  3. Tried to change the font size of the image - wut?

There has to be a simple way to do this. Thanks in advance.

like image 676
Rob Norback Avatar asked Jan 21 '20 04:01

Rob Norback


2 Answers

You can use the Default Symbol Configuration settings on the UIButton in the Attributes Inspector to accomplish the same thing. All Credit to Andrew Kirna below. Thanks dude!

Default Symbol Configuration


Success!!! I finally figured out how to do this, thanks to a great article on SF Symbols. It was certainly buried in there.

It would be really nice to resize your button images in storyboard wouldn't it? I thought so at least.

  1. Add IconButton.swift to your project in Xcode.

    import UIKit
    
    @IBDesignable
    class IconButton: UIButton {
        @IBInspectable var pointSize:CGFloat = 30.0
    
        override func layoutSubviews() {
            super.layoutSubviews()
            if #available(iOS 13.0, *) {
                let config = UIImage.SymbolConfiguration(pointSize: pointSize)
                setPreferredSymbolConfiguration(config, forImageIn: .normal)
            } else {
                // Fallback on earlier versions
            }
        }
    }
    
  2. Create a button in storyboard with an SF icon as the image.

  3. Go to the identity inspector and make the class of your button IconButton

  4. Go to the attribute inspector and enter in your point size. Note that this the height of the icon x 3/4. I wanted a 40 x 40 icon, so my point size was 30.

  5. See your icon update in storyboard and laugh happily that you didn't spend 3 hours figuring this out :D

Some credit to the great article: https://www.avanderlee.com/swift/sf-symbols-guide/

like image 68
Rob Norback Avatar answered Sep 21 '22 06:09

Rob Norback


This works for me (if you want it programmatically):

let config = UIImage.SymbolConfiguration(
    pointSize: 32, weight: .medium, scale: .default)
let image = UIImage(systemName: "magnifyingglass", withConfiguration: config)
button.setImage(image, for: .normal)
like image 36
algrid Avatar answered Sep 21 '22 06:09

algrid