I'm new to swift and watching a tutorial on how to toggle the background colour and text of a button when it is clicked.
The problem is, the background colour and text do not change when the button is clicked.
The function, which is identical to the instructor's and works on his laptop is :
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
}
}
I call the function with:
@IBAction func callFlip(_ sender:UIButton){
flipcard(withEmoji: "em", on: sender)
}
I have searched for a solution but they all seem to refer to older versions of Xcode and swift.
Nevertheless i have tried to to replace
button.setTitle(emoji, for: UIControl.State.normal)
with
button.setTitle(emoji, for: UIControl.State(rawValue:UInt(0)))
and
button.setTitle(emoji, for: [])
as suggested here with the same result :( . How can i get this to work please?
Im using Xcode 10.1 (10B61). Does the version of Xcode matter?
cheers
答案 0 :(得分:0)
Tested this, with a button with title FlipColor and get the inverting effect.
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)
}