jazzedge
11/25/2017 - 7:08 PM

Swift - Extension for a Round Button*

Create a swift file as below. Add a button using Storyboard Set the class in Attributes Inspector as RoundButton

Source: BorgGreen

UPGRADE NOTE: Remove this class and replace with a more 
generic UIView Extension: https://spin.atomicobject.com/2017/07/18/swift-interface-builder/


01. Create a class extension file

import UIKit
@IBDesignable
class RoundButton: UIButton {
    
    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            self.layer.cornerRadius = cornerRadius
        }
    }
    
    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            self.layer.borderWidth = borderWidth
        }
    }
    
    @IBInspectable var borderColor: UIColor = UIColor.clear {
        didSet {
            self.layer.borderColor = borderColor.cgColor
        }
    }
    
    @IBInspectable var shadowRadius: CGFloat = 0 {
        didSet {
            self.layer.shadowRadius = shadowRadius
        }
    }
    
    @IBInspectable var shadowColor: UIColor = UIColor.clear {
        didSet {
            self.layer.shadowColor = shadowColor.cgColor
        }
    }
    
    @IBInspectable var shadowOffset: CGSize = CGSize.zero {
        didSet {
            self.layer.shadowOffset = shadowOffset
        }
    }
    @IBInspectable var shadowOpacity: Float = 1.0 {
        didSet {
            self.layer.shadowOpacity = shadowOpacity
        }
    }
    
}

02. Set up in VC using storyboard:

@IBOutlet weak var btnProfilePlus: RoundButton!

03. Modify the button inyour VC (in this example to include a Font Awesome image):

        //FontAwesome Buttons (Set PLUS for round button)
        self.btnProfilePlus.setTitle(Constants.iconLibrary.plus.rawValue, for: .normal)
        self.btnProfilePlus.titleLabel!.font = UIFont(name: Constants.iconFont.fontAwesome.rawValue, size: CGFloat(Constants.iconSize.small.rawValue))
        self.btnProfilePlus.setTitleColor(UIColor(named: .white), for: .normal)