在 Swift 中创建 Default-Style UIButton

Creating Default-Style UIButton in Swift

当我在 Swift 中创建 UIButton 时,例如通过

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

我得到的按钮样式似乎与我在 Interface Builder 中添加按钮时得到的样式不同。具体来说,标题颜色是白色而不是默认的 "tint color",使按钮不可见。现在我希望这个按钮看起来像任何其他按钮,所以我不想指定我自己的颜色。

可以通过以下方式设置正常(未按下)状态:

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

到目前为止,还不错。但是按下按钮时文本颜色不会改变。我想,为此我需要

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

理想情况下无需对颜色进行硬编码,我需要在上面替换什么才能获得默认的按下按钮颜色?或者是否有更简单的方法来创建具有默认样式的 UIButton

为了声明与 storyboard/interface 构建器中相同(默认)样式的按钮,请使用以下代码对其进行实例化:

let aButton = UIButton(type: .system)

否则按钮的类型为custom

您可以了解各种按钮类型 here