【问题标题】:Correct and incorrect answer in SwiftSwift 中的正确和错误答案
【发布时间】:2017-05-21 04:17:14
【问题描述】:

我正在制作关于欧洲国家的简单测验应用程序,我有一张地图和下面三个带有国家名称的按钮,其中一个是正确的,当然还有两个是错误的。我想将不正确的(如果用户单击不正确的按钮)按钮突出显示为红色并纠正为绿色,如果用户单击正确的按钮我想将其突出显示为绿色,并且可能在 5 秒后恢复到最初的相同颜色。我知道如何更改按钮颜色,但我不知道如何在 5 秒内执行此操作并返回默认颜色。我怎样才能做到这一点 ?在我用来更改按钮颜色的代码下方

UIButtonOutlet.Backgroundcolor.Uicolor.green 

但它的默认绿色,所以我不能设置我的颜色。

【问题讨论】:

  • 你也想要同样的错误答案吗?
  • 对于不正确的我想突出显示红色不正确的按钮和绿色正确的 5 秒

标签: swift button uibutton swift3


【解决方案1】:

你可以试试这样的。首先在您的类中声明一个UIButton 实例,然后在将按钮的backgroundColor 设置为正确和不正确后,再声明scheduledTimer,并将该按钮引用与您首先创建的按钮一起存储。

var selectedButton = UIButton()

现在在设置按钮的backgroundcolor 时使用这个selectedButton

btnOutlet.backgroundcolor = .green //For correct
btnOutlet.backgroundcolor = .red //For incorrect
self.selectedButton = btnOutlet
//Now scheduled the timer for 5.0 sec
Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(setButtonBGBack), userInfo: nil, repeats: false)

在你的类中添加setButtonBGBack 方法

func setButtonBGBack() {
    self.selectedButton.backgroundcolor = .blue //Set to default here
    self.selectedButton = UIButton()
}

【讨论】:

  • 看来我们的想法基本一致
  • 谢谢 :),但是如果我从这个圆圈中选择按钮的颜色和颜色(不知道怎么说我英语:))那么我该如何设置呢?
  • Welcome mate :) 你说的是什么意思设置这个?
  • self.selectedButton.backgroundcolor = .blue //这里设置为默认我的按钮在黄色和棕色之间,所以我不能写.blue,我该如何设置我的颜色?
  • @K.Pilch 你能指定你在什么基础上设置button的背景颜色吗?
【解决方案2】:

假设您有更改“changeColor”函数中颜色的代码:

var correctButton: UIButton

func changeColor() {
    if correctButton.backgroundColor == .green {
        correctButton.backgroundColor = .lightGray //back to original color
    }
}

如果在调用 func 时它是绿色的,这实际上是将正确的按钮颜色更改回其默认值(无论可能是什么)。

现在要使用它,我们可以在连接到每个按钮的 IBAction 内部做一些工作:

@IBAction func buttonClicked(sender: UIButton) {
    if sender.titleLabel?.text == "Correct Answer" {
        button.backgroundColor = .green

        correctButton = button //set the correct button variable so the changeColor func can be used
        let timer = Timer.init(timeInterval: 5, target: self, selector: #selector(changeColor), userInfo: nil, repeats: false)
    } else if sender.titleLabel?.text == "False Answer 1" || sender.titleLabel?.text == "False Answer 2" {
        button.backgroundColor = .red
    }

}

所以在这段代码中,如果你点击了正确答案的按钮(你可以通过标签或其他方式来识别它,但我只是决定使用它的文本)然后颜色立即设置为绿色,然后设置了正确的按钮变量,但随后启动了一个计时器,五秒钟后将调用您的 changeColor 函数,然后将其更改回其原始颜色。

希望这会有所帮助:)

编辑

当然,我的方法假设您使用情节提要来创建这些按钮。如果您以编程方式创建它们,那么 NiravD 的方法会更好。

【讨论】:

  • 您在这里遇到了错误,Timer 唯一可以为方法添加的选择器是 changeColor()changeColor(timer: Timer),您不能使用 Timer 选择器传递 UIButton 实例。跨度>
  • @NiravD 是的,我忽略了这一点。感谢您指出了这一点。那我会用稍微不同的方法更新代码。
猜你喜欢
  • 1970-01-01
  • 2012-12-31
  • 2014-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
相关资源
最近更新 更多