0

Is there a way to create a button using swift and have it use the default behavior that you would see when just dragging a button out in the Interface Builder?

Creating a button with interface builder gives the default "this is an interactive element" blue to the text/title as well as a color lightening changing effect when it is touched/tapped.

Creating a button with swift just using let myButton = UIButton() defaults the text AND background color to white(???) and no visual activity indication. I've found that you can set the title color to self.view.tintColor for every button, but just hoping there might be a better way to "default" it.

Case Silva
  • 466
  • 7
  • 26
  • 1
    Check the other init method: `init(type:)`. – Larme May 22 '19 at 19:50
  • Unless you override `UIButton` programatically all of your buttons will have to have properties manually changed. Or you will have to declare your button's style in every view. You have to override the standard implementation of the Apple `UIButton` which is a white button with blue text. I'm not sure if there is a way to do this on the Storyboards. – KSigWyatt May 22 '19 at 20:17
  • Am I doing something wrong? In my example I WANT the standard white background with blue text and default interaction indication. I'm instead getting white text on white background with no interactivity indication. I'm doing a simple ```let myButton = UIButton()``` ```self.view.addSubview(myButton)``` – Case Silva May 22 '19 at 20:31

2 Answers2

1

The correct way to create a button in Swift with the same default behaviour as if using the Interface Builder is using the init(type:) method of UIButton as Larme commented.

Example:

let btn = UIButton(type: .system)

This creates a button with the standard blue text and visual activity indication.

I found information on this and the other UIButton types you can use here.

Jacob Wrenn
  • 448
  • 5
  • 14
0

You can subclass UIButton and recreate all the touches / title colors etc..

Or

You can create extensions

Found an extension from this link..

how to set UIButton type in UIButton Subclass

extension UIButton {
    static func createStandardButton() -> UIButton {
        let button = UIButton(type: UIButtonType.system)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button.setTitleColor(UIColor.black, for: .normal)
        button.setTitleColor(UIColor.gray, for: .highlighted)
        return button
    }
}

let button = UIButton.createStandardButton()
Mocha
  • 2,035
  • 12
  • 29