【问题标题】:Creating Default-Style UIButton in Swift在 Swift 中创建默认样式的 UIButton
【发布时间】:2015-07-29 12:58:59
【问题描述】:

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

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

如果我在 Interface Builder 中添加一个按钮,我似乎没有得到相同的按钮样式。具体来说,标题颜色是白色而不是默认的“色调颜色”,使按钮不可见。现在我希望这个按钮看起来像任何其他按钮,所以我不想指定自己的颜色。

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

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

到目前为止,一切都很好。但是按下按钮时文本颜色不会改变。我想,为此我需要

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

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

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

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

    let aButton = UIButton(type: .system)
    

    否则按钮的类型为custom

    您可以阅读有关各种按钮类型的信息here

    【讨论】:

    • let button = UIButton(type: UIButtonType.System)
    • let aButton = UIButton(type: .system)
    • @brokenrhino 感谢您指出这一点!从 2016 年的 Swift 3 开始,枚举值变为小写。将更新答案。
    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多