Correct and incorrect answer in Swift - 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.

Related

Refresh UIButton text with fade animation

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 :)

How do i add doneaction and change the done text?

I am using IQKeyboardManager and i added custom action for the done button
txtfield.addDoneOnKeyboard(withTarget: self, action: #selector(doneButtonClicked), titleText: "Next")
IQKeyboardManager.shared().toolbarDoneBarButtonItemText = "Next"
#objc func doneButtonClicked(_ sender: Any) {
// do stuff
}
Here the action gets called and everything works. But the title of the donebutton is DONE (in bluecolor).
The "Next" is show at the middle of the keyboard as titletext. How do i change the text/color of the done button? If i dont add any action to any specific textfield, the second line works perfectly , but anytime i add action, the custom name for done button is ignored.
Any help?
IQKeyboardManager in github
Use the following:
let config = IQBarButtonItemConfiguration(title: "Next", action: #selector(doneButtonClicked))
txtfield.addKeyboardToolbar(withTarget: self, titleText: nil , rightBarButtonConfiguration: config, previousBarButtonConfiguration: nil, nextBarButtonConfiguration: nil)
// any color you like
txtfield.keyboardToolbar.doneBarButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: UIControl.State.normal)
Instead of:
txtfield.addDoneOnKeyboard(withTarget: self, action: #selector(doneButtonClicked), titleText: "Next")
what is more? titleText sets toolbar.titleBarButton.title.
I pick some code snip from IQKeyboardManager source code here:
//Title button
toolbar.titleBarButton.title = titleText
while toolbarDoneBarButtonItemText set's doneBarButton.title
some code snip from IQKeyboardManager here:
if let rightConfig = rightBarButtonConfiguration {
var done = toolbar.doneBarButton
if rightConfig.barButtonSystemItem == nil && done.isSystemItem == false {
done.title = rightConfig.title
done.image = rightConfig.image
done.target = target
done.action = rightConfig.action
}
Try this one.
import IQKeyboardManagerSwift
IQKeyboardManager.shared.toolbarDoneBarButtonItemText = "NEXT"
See below picture has the NEXT button in Xcode 10.1.

How do I make a UIButton have the correct appearance with image and text?

I have a UIButton that has both an image and text in it. I am quite happy with its appearance except for when it is pressed.
Before it is pressed it looks like this:
After it is pressed it looks like this:
I am used to the appearance darkening the entire button when pressed, but for some reason when I have both an image and text is designates all the coloration to the image. I am quite aware that I can just make the entire button an image, but I am trying to keep this project as away from that style as possible. All of my other button are created with no images.
Is there any way to make the entire button darken as it normally would as it is currently setup?
You have to set the UIButton to Custom type (no System type) and change that properties:
self.yourButton.adjustsImageWhenHighlighted = false
If I get what you want try with that code:
override func viewDidLoad() {
super.viewDidLoad()
self.button.backgroundColor = UIColor.redColor()
}
#IBAction func buttonClicked(sender: UIButton) {
//Touch Up Inside action
sender.backgroundColor = UIColor.redColor()
}
#IBAction func buttonReleased(sender: UIButton) {
//Touch Down action
sender.backgroundColor = UIColor.grayColor()
}
Normal:
Pressed:
The simplest solution would be to match the text's highlight color:
button.setTitleColor(UIColor.gray, for: UIControlState.highlighted)

Swift UIButton not appearing on screen

I have a view in my tabbar controller where I would like to show a button. I create this button programmatically based of a condition, therefore I use the following code but nothing is appearing:
override func viewDidLoad() {
super.viewDidLoad()
if !Settings.getIsConnected() {
notConnected()
}
}
func notConnected() {
let connectBtn = UIButton(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 200, height: 45))
connectBtn.setTitle("Connect", forState: .Normal)
connectBtn.addTarget(self, action:#selector(self.pressedConnect(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(connectBtn)
print("Button created")
}
func pressedConnect(sender: UIButton!) {
}
I am clueless on what I am doing wrong. Anyone got suggestions? Cause it does print out "Button created" so it definitely runs the code inside the noConnected() method.
Add a background color to your UIButton and add a tint color to the title. This will resolve the problem
Try moving the code to viewDidAppear and see if the button is showing up.
The frame is not correctly set when in viewDidLoad. Use the method viewDidLayoutSubviews for the earliest possible time where the frame is correctly setup for a ViewController.
With this code change, you will need some additional logic for when your button should be added as a subview though.
A programmatically created button may not show up because of more reasons, e.g:
the tint color is not set
the background color is not set
the button is not added to the view hierarchy
the button is hidden
In your case, you should change the tint color or the background color of your button.
E.g.:
Swift 4.2:
private lazy var connectButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .green
button.setTitleColor(.black, for: .normal)
button.setTitle(NSLocalizedString("Connect", comment: ""), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(connectButton)
}
You can re-check the button properties in the storyboard that it is not hidden.

Changing color of button text and state

I need to change the color of my button's text.
I also need to change the state to Disabled after the user presses it.
I have no idea how to do this. I've been looking things up for a while but they're all either in objective C or I can't understand it (usually help docs, they're stupid.).
In swift you change color for a specific State with the setTitleColor method.
In you case it will be :
button.setTitleColor(UIColor.grayColor, forState: UIControlState.Normal)
Swift 5 Update:
button.setTitleColor(UIColor.grayColor, for: UIControl.State.normal)
To change color of text
button.titleLabel.textColor = UIColor.grayColor()
To change state, on button press add following -
button.enabled = true
IBAction method should be like -
#IBAction func buttonTapped(sender : UIButton!) {
sender.enabled = false
}
Swift 3
button.setTitleColor(UIColor.gray, for: UIControlState.normal)
Note that;
grayColor has been renamed to gray
Normal is now normal (lowercase)
You have to set the text colour for the specific button state.
For Swift3, try below code :
#IBAction func butnClicked(sender : UIButton) {
sender.setTitleColor(.red, for: .normal)
sender.isEnabled = false
}
Set Enabled and text color from story board.