Creating a default UIButton in Swift

When I create a UIButton in Swift, for example. by

 let aButton = UIButton() aButton.setTitle("Title", forState: UIControlState.Normal) 

It looks like I am not getting the same button style as I would if I added a button in Interface Builder. In particular, the title color is white, instead of the standard hue color, leaving the button invisible. Now I want this button to look like any other button, so I do not want to specify my own colors.

Setting the normal (not pressed) state can be done using

 aButton.setTitleColor(self.tintColor, forState: UIControlState.Normal) 

So far so good. But when the button is pressed, the text color does not change. I think for this I need

 aButton.setTitleColor(/* somehting here */, self.tintColor, forState: UIControlState.Highlighted) 

Ideally, without hard color coding, what do I need to replace above to get the button color of the pressed button by default? Or is there an even simpler way to just create a UIButton with a default style?

+4
source share
1 answer

To declare a button of the same style (default) as in the storyboard / interface builder, use the following code to create it:

 let aButton = UIButton(type: UIButtonType.System) 

Otherwise, the button is of type custom .

You can read about the different types of buttons here .

+5
source

All Articles