Search code examples
swiftuibuttonextension-methods

How do I call a function that I have defined in an extension on a button?


I have written the following function into my UIButton extension:

extension UIButton {
func detail(_ font: String, _ fontSize: CGFloat, _ cornerRadius: CGFloat) -> UIButton {
        let button = UIButton()
        button.titleLabel?.font = UIFont(name: font, size: fontSize)
        button.layer.cornerRadius = cornerRadius
        return button
    }
}

However, when I try to call this function in my viewDidLoad(), I get the following error:

 override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(theButton)
        theButton.detail("Avenir", 50, 12) // ERROR: Result of call to 'detail' is unused
}

How can I fix this?


Solution

  • There is error because your function has return value. Change your code to:

    let resultButton = UIButton()
    resultButton = theButton.detail("Avenir", 50, 12)