【问题标题】:How to change the background color of a UIButton when tapped in swift?swift - 快速点击时如何更改UIButton的背景颜色?
【发布时间】:2015-06-02 20:58:06
【问题描述】:
ViewController: UIViewController {
   @IBAction func like(sender: AnyObject) {
       like(backgroundColor!) = UIColor.greenColor()
   }
}

我想改变 UIbutton“like button”的颜色: 白色是默认的“未点击或不同” 点按时为绿色。

如何在使用 Swift 时更改按钮的背景颜色?

【问题讨论】:

    标签: ios swift uibutton ibaction


    【解决方案1】:

    按钮不是like——这是方法的名称。您可以通过sender访问该按钮。

    @IBAction func like(sender: AnyObject) {
        (sender as UIButton).backgroundColor = UIColor.greenColor()
    }
    

    或者更简洁:

    @IBAction func like(button: UIButton ) {
        button.backgroundColor = UIColor.greenColor()
    }
    

    【讨论】:

    • 它就像魔术一样!但为什么颜色没有填充 png 图像?非常感谢
    • @JAMESMATHEO12 我不明白你的意思,但听起来你的 png 图像在你期望的地方实际上并不透明。
    • @JAMESMATHEO12 哦,UIButton 自然是矩形的,所以你必须添加一个圆角半径以使其变为圆形。
    猜你喜欢
    • 2021-11-04
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多