Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Default-Style UIButton in Swift

When I create a UIButtonin Swift, e.g. by

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

it seems like I'm not getting the same button style as I would get if I added a button in Interface Builder. Specifically, the title color is white instead of the default "tint color", leaving the button invisible. Now I want this button to look like any other button, so I don't want to specify my own colors.

Setting the normal (not pressed) state can be done with:

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

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

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

Ideally without hardcoding the color, what do I need to substitute above to get the default pressed button color? Or is there even a simpler way to just create a UIButton with default style?

like image 209
jerry Avatar asked Jul 29 '15 12:07

jerry


1 Answers

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

let aButton = UIButton(type: .system)

Otherwise the button is of type custom.

You can read about the various button types here.

like image 160
ZeMoon Avatar answered Sep 21 '22 21:09

ZeMoon