我是 swift 的新手,正在观看有关如何在单击按钮时切换按钮的背景颜色和文本的教程。
问题是,单击按钮时背景颜色和文本不会更改。
该功能与讲师的功能相同,并且可以在他的笔记本电脑上工作:
func flipCard(withEmoji emoji: String, on button: UIButton){
if button.currentTitle == emoji{
button.setTitle("", for UIControl.State.normal)
button.backgroundColor = UIColor.red
}else{
button.setTitle(emoji, for UIControl.State.normal)
button.backgroundColor = UIColor.white
}
}
我调用该函数:
@IBAction func callFlip(_ sender:UIButton){
flipcard(withEmoji: "em", on: sender)
}
我已经寻找了一个解决方案,但它们似乎都指的是旧版本的 Xcode 和 swift。
尽管如此,我还是试图取代
button.setTitle(emoji, for: UIControl.State.normal)
跟
button.setTitle(emoji, for: UIControl.State(rawValue:UInt(0)))
和
button.setTitle(emoji, for: [])
按照此处的建议,结果:(相同。请问我怎样才能让它工作?
我使用的是Xcode 10.1(10B61)。Xcode 的版本重要吗?
干杯
测试了这一点,使用标题为FlipColor的按钮并获得反转效果。
func flipCard(withEmoji emoji: String, on button: UIButton){
if button.currentTitle == emoji {
button.setTitle("", for: UIControl.State.normal)
button.backgroundColor = UIColor.red
button.tintColor = .yellow
}else{
button.setTitle(emoji, for: UIControl.State.normal)
button.backgroundColor = UIColor.white
button.tintColor = .red
}
}
@IBAction func flipMyColor(_ sender: UIButton) {
flipCard(withEmoji : "FlipColor", on: sender)
}