Refresh UIButton text with fade animation - swift

I'm trying to implement a simple QRScanner app that presents a button, if a QR code is scanned. Now I want to present the same button for multiple QR codes, but in case two QR codes are scanned one after the other, and both codes present the same button, I want to shortly refresh the button text with a fade animation in order to indicate that a new QR code has been scanned. I noticed that if you change the button title, that animation is triggered but if you set it to a string identical to its current title, it doesn't show any animation anymore. I was wondering if there's a simple way to trigger that same animation even if I don't want to change the title's value. Here's my code excerpt:
func setValidMessageLabel() {
messageLabel.backgroundColor = color
messageLabel.setTitle("Check Now", for: .normal)
messageLabel.setTitleColor(.white, for: .normal)
}
func setInvalidMessageLabel() {
messageLabel.backgroundColor = UIColor(white: 0.7, alpha: 0.6)
messageLabel.setTitle("Invalid Code", for: .normal)
messageLabel.setTitleColor(.white, for: .normal)
}
if metadataObj.stringValue != nil && metadataObj.stringValue != key {
key = metadataObj.stringValue
messageLabel.isEnabled = true
switch key {
case cokeWin:
setValidMessageLabel()
case cokeLose:
setValidMessageLabel()
default:
setInvalidMessageLabel()
return
}
}
Happy for any help :)

Related

How can I change the placeholder (label) color for MDCOutlinedTextFields?

I'm having a hard time changing the text color for the placeholder label that is used as a hint when not in focus and as a label on top when in focus. (Photo below)
The is reason I'm switching out all my MDC-TextFields and MDC-TextInputControllers is because they are all being deprecated for the New MDC-Outlined Textfields.
The code below is a function within an extension that would simply setup the general background & sub-label colors for all MDC-Outlined Textfields throughout the app.
I have tried a number of functions with no luck(commented out below).
extension MDCOutlinedTextField {
func setUpGeneralBackgroundColors(){
//Text color
self.setTextColor(UIColor.white, for: .normal)
self.setTextColor(UIColor.white, for: .editing)
//Border color
self.setOutlineColor(UIColor.white, for: .normal)
self.setOutlineColor(UIColor.white, for: .editing)
//self.setFloatingLabelColor(UIColor.white, for: .normal)
//self.setFloatingLabelColor(UIColor.white, for: .editing)
//self.setFloatingLabelColor(UIColor.white, for: .disabled)
// self.setNormalLabelColor(UIColor.purple, for: .normal)
// self.setNormalLabelColor(UIColor.purple, for: .editing)
// self.setNormalLabelColor(UIColor.purple, for: .disabled)
// self.label.tintColor = UIColor.purple
//self.label.textColor = UIColor.systemPink
//self.label.shadowColor = UIColor.cyan
//self.label.backgroundColor = UIColor.red
//Changes icon colors within the text field if any
self.tintColor = .green
}
}
I figured the problem, in the storyboard where I have these new textfields I had a raw string for the placeholder which override the swift code behind the scenes and prevented me from changing colors.
Note: This problem will NOT occur with the now deprecated MDC-Textfields.
If you guys have a placeholder value in the storyboard when using these MDC-Outlined Textfields in storyboards, (not to mixed up with the swift code) then get rid of them.

How can I change my custom cell background when pressing a button?

I have a CollectionView and a Button inside of an UIView. The purpose of the button is change the theme of the app, and I can change all colors, except for the backgroundColor of a nameContainerView on my TatodexCell (a custom cell).
I can't figure out how to access that property, and then, change the color I want.
THE FOLLOWING CODE IS LOCATED ON MY TatodexController FILE
My button property is:
let buttonChangeTheme: UIButton? = {
let button = UIButton()
button.setTitle("Change to blue theme", for: .normal)
button.addTarget(self, action: #selector(themeButtonClicked), for: .touchUpInside)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.layer.borderWidth = 3
button.layer.borderColor = Colors.mainBlack?.cgColor
button.backgroundColor = Colors.darkBlue
button.tintColor = Colors.mainWhite
return button
}()
My button-func is this one:
#objc func themeButtonClicked() {
clickCheck = !clickCheck
if clickCheck {
navigationController?.navigationBar.barTintColor = Colors.lightBlue
collectionViewPokemon?.backgroundColor = Colors.darkBlue
buttonChangeTheme?.backgroundColor = Colors.darkRed
buttonChangeTheme?.setTitle("Return to red theme", for: .normal)
}
else {
navigationController?.navigationBar.barTintColor = Colors.lightRed
collectionViewPokemon?.backgroundColor = Colors.darkRed
buttonChangeTheme?.backgroundColor = Colors.darkBlue
buttonChangeTheme?.setTitle("Change to blue theme", for: .normal)
}
}
THE FOLLOWING CODE IS LOCATED ON MY TatodexCell FILE
The nameContainerView I wanna modify it's bg color is:
lazy var nameContainerView: UIView = {
let nameView = UIView()
nameView.backgroundColor = Colors.lightRed
nameView.addSubview(nameLabel)
nameLabel.center(inView: nameView)
return nameView
}()
My goal is to change nameView.backgroundColor = Colors.lightRed to nameView.backgroundColor = Colors.lightBlue, but I can't access that property.
I would really appreciate any help or advice. Perhaps the solution is hiding in plain sight, but I've tried many ways and none of them worked. Let me know if another chunk of code is needed to be shown.
If you implement the tintColorDidChange() method in your custom collection view cell, and in that method, you set the cell's background color to the tint color, then when you change the owning UICollectionView's tint color, the cells's tintColorDidChange() methods will fire and you'll see the change.

How to update buttons status when the user reopens the app? (Swift 5)

I have a question about saving the last status of the buttons for a "Hung Person" game. By using UserDefaults I was able to save almost all the status of the user when the game was closed (Screen1 shows the user's game status while playing), as you can see, the user chose 2 wrong letters that were not in the hidden word (M and N, which are in red and disabled) and the user correctly guessed the O, B, C letters (which disappeared from the alphabet and also are disabled).
When the user closes the app and when it is reopened again, I was able to reload almost all the previous data of the last session played, except for the buttons status. You can see this in Screen2. I used UserDefaults to save and load the game. I save the status of the game every time the user taps on any button (trying to guess the hidden word's characters), and I load the data back in viewDidLoad().
The game is made programmatically, I created the buttons using something like the following:
for row in 0..<5 {
for column in 0..<6 {
if counterLetter < 26 {
let letterButton = UIButton(type: .system)
letterButton.titleLabel?.font = UIFont.systemFont(ofSize: titleLabelFontSize)
letterButton.setTitle(englishAlphabet[counterLetter], for: .normal)
letterButton.isHidden = false
letterButton.isEnabled = true
letterButton.alpha = 1
letterButton.setTitleColor(.red, for: .disabled)
letterButton.addTarget(self, action: #selector(letterTapped), for: .touchUpInside)
letterButton.layer.borderWidth = 1
letterButton.layer.borderColor = UIColor.black.cgColor
// Button's frame creation
let frame = CGRect(x: column*widthButton, y: row*heightButton,
width: widthButton, height: heightButton)
letterButton.frame = frame
buttonsView.addSubview(letterButton)
letterButtons.append(letterButton)
counterLetter += 1
} else {
continue
}
}
}
It is in the letterTapped method (inside the #selector(letterTapped) part in the previous code) where I save the user's progress when any alphabet button is tapped. As I said before, I recall the player's last status in viewDidLoad().
I tried to save the buttons status inside the letterTapped method as well, but I haven't been able to save or reload the buttons status as the player's had.
Can you give me please a hand about where I have to use userDefaults to save the last session status of the alphabet buttons, please? So that when the players reopens the app, the screen2 is the same as screen1.
If you need me to share my code, I can do willingly it.
Thanks in advance.
Regards!
What you are looking for is a K.V.O called "UIApplicationWillEnterForeground" and "UIApplicationDidEnterBackground"
In your viewDidLoad of your ViewController you should do the following:
func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
then implement these function in the same ViewController:
func appMovedToForeground() {
print("Application moved to Foreground!")
}
func appMovedToBackground() {
print("Application moved to Background!")
}
now when your app goes to the background or returns to the foreground those functions will get called

Correct and incorrect answer in Swift

I'm making simple quiz app about countries in Europe, I have a map and three buttons below with names of countries, one of them is correct and of course two incorrect. I want to highlight incorrect (if user click incorrect button) button for red and correct for green, if user click correct button I want to highlight it for green and after maybe 5s come back to the same color that was at first. I know how to change button color but I don't know ho do that for 5s and come back to default color. How can I do that ? Below its code that I use to change button color
UIButtonOutlet.Backgroundcolor.Uicolor.green
But its default green, so I can't set my color.
You can try something like this. First declare one UIButton instance in your class and then scheduledTimer after setting backgroundColor of button for correct's and incorrect and store that button reference with button that you have created first.
var selectedButton = UIButton()
Now use this selectedButton when you are setting button's backgroundcolor.
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)
Add the setButtonBGBack method in your class
func setButtonBGBack() {
self.selectedButton.backgroundcolor = .blue //Set to default here
self.selectedButton = UIButton()
}
Lets say you have your code for changing the color which is in the "changeColor" func:
var correctButton: UIButton
func changeColor() {
if correctButton.backgroundColor == .green {
correctButton.backgroundColor = .lightGray //back to original color
}
}
What this essentially does is changes your correct button color back to its default (whatever that may be) if it is green when the func is called.
Now to use this, we can do a little work inside of the IBAction that is connected to each of your buttons:
#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
}
}
So in this code, if you click the button that is the correct answer (you can identify this by tag or other means, but I just decided to use its text) then the color is set to green immediately, and then the correctButton variable is set, but then a timer is initiated that after five seconds will call your changeColor func and then change it back to its original color.
Hope this helps :)
Edit:
Of course, my method assumes that you are using the storyboard to create these buttons. If you are creating them programmatically, then NiravD's method will work better.

Changing colour on buttons in tableview cell edit actions

Hello!
Having a go at swipe-to-delete functions and the likes in tableView cells today...
When toggling a button I would like it to change colours from green to red and back again. - Any suggestions on how to achieve this?
For the toggle button I have declared a boolean which is set
to false at start.
and this is what I've got inside editActionsForRowAtIndexPath:
...
let toggleAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Toggle", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
let button: UIButton = UIButton()
button.backgroundColor = UIColor.greenColor()
if(self.toggleBool == false) {
self.toggleBool = true
button.backgroundColor = UIColor.redColor()
} else {
self.toggleBool = false
toggleButton.backgroundColor = UIColor.greenColor()
}
self.view.addSubview(button)
})
return [deleteAction, toggleAction]
}
The code snippet above does not make the button change colour when pressed!
Any help in the matter would be much appreciated!