Swift Xcode 6 If Else statement check letters or numbers - swift

I am trying to write and if else statement.
I need it to check if atextField is empty or has letters and if the textfield is empty or has letters is triggers a UIAlertWIndow.
I have tried boolean methods to no avail.
Any ideas?
This is what I have written so far:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if self.numOfGuestsData.text == "" {
alert()
println("Something Amish")
let alertController = UIAlertController(title: "Split The Bill", message:
"Please Enter The Number of Guests!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil))
presentViewController(alertController, animated: true, completion: nil)
} else if self.numOfGuestsData.text != "" {
let subTotalVC = segue.destinationViewController as subTotalAmountViewController
subTotalVC.numOfGuests = numOfGuestsData.text
println("everything is Ok Here")
}
}
Also if I take out the alert window the if else statement fails for some reason.
Like if I write it like this:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if self.numOfGuestsData.text == "" {
alert()
println("Something Amish")
} else if self.numOfGuestsData.text != "" {
let subTotalVC = segue.destinationViewController as subTotalAmountViewController
subTotalVC.numOfGuests = numOfGuestsData.text
println("everything is Ok Here")
}
}
It just goes to the else...

Are you trying to suppress the segue if the textField is empty and present a UIAlertController instead if that is the case? Are you using a show segue? I think your logic needs to be moved out of prepareForSegue: and moved into shouldPerformSegueWithIdentifier:. Do your check in that method. Doing the logic in prepareForSegue: is too late; the segue is definitely going to happen by then.
Basically, you'll override shouldPerformSegueWithIdentifier: and then either return true or return false based on your logic. If it returns false, the segue won't happen.
Documentation here.

Related

Unable to get buttons currentTitle from UIStoryBoardSegue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Choose Theme" {
if let themeName = (sender as? UIButton)?.currentTitle {
if let theme = themes[themeName] {
if let cvc = segue.destination as? ConcentrationViewController {
cvc.theme = theme
}
} else {
print("something went wrong")
}
} else {
print("couldnt get current title")
}
}
}
There is the code. I'm trying to get senders current title. I tried debugging and it prints "couldn't get current title", the value that I'm getting is nil.
What am I doing wrong?
Thanks in advance
Instead of using currentTitle, you might want to try titleLabel?.text. It seems to be more reliable. I got your program to work (tested in Xcode) using this change.

Is there a way to write an if statement based on if a button was pressed on another view controller previously?

I'm trying to create a calculator that displays a result to the user about their college grades. The user taps buttons and based on their selections, the UI view updates and displays the next question. My code works when up until I need it to access a previously tapped button that was selected previously and on a different view controller. The problem that I'm having specifically is on one view controller, the user can select if they want to know Calculation1 (associated with top button with sender.tag == 1) or Calculation2 (bottom button, sender.tag == 2). Regardless of which button is pressed, a segue is performed to the same question on a new view controller. After that mutual question is answered, there is only one button to press. I'm trying to code an if statement for if Calculation1 (from previous VC) was selected then update the view to the next question, and if Calculation2 was selected perform a segue to a different VC for the next question. The way I was trying to use the boolean was as a property from the previous VC. The if statement isn't working and instead, the same action happens regardless of the selection.
This is for an iOS app with Swift using Xcode. I attempted to create a boolean as a property so that when Calculation1 is tapped, findCalc1 = true and then accessing that boolean as a property in the next VC but it didn't work. I also tried preparing a boolean for the segue to the mutual question but it didn't work either. I feel like I have a gap in my understanding of what can and cannot be performed between different VCs.
// Here is my code for the first VC
#IBAction func lightButtonPressed(_ sender: UIButton) {
if sender.tag == 1 && lightViewPromptIndex == 1 {
desiredGpaText = textfield.text!
performSegue(withIdentifier: "goToDarkButtonVC", sender: self)
} else if sender.tag == 2 && lightViewPromptIndex == 1 {
performSegue(withIdentifier: "goToDarkButtonVC", sender: self)
}
// Here is my code for the second VC
#IBAction func darkButtonPressed(_ sender: Any) {
if aboveTopPromptIndex == 1 && lightViewObject().findCalc1 == true {
aboveTopTextPrompt.text = aboveTopPrompt2
topTextfield.placeholder = "Ex: 76.00"
besideTopTextLabel.isHidden = true
underTopTextLabel.text = "course credits"
aboveBottomTextPrompt.text = "that count toward my GPA."
bottomTextfield.isHidden = true
underBottomTextLabel.isHidden = true
bottomFloatingLabel.isHidden = true
darkButton.setTitle(nextTitle, for: .normal)
aboveTopPromptIndex = 2
} else if aboveTopPromptIndex == 1 && lightViewObject().findCalc1 == false {
performSegue(withIdentifier: "darkViewToABC", sender: TextfieldTwoLightButtonsViewController.self)
The mutual question has aboveTopPromptIndex == 1. What I would like to happen is if that question is asked and Calculation1 was previously selected, for the first chunk of code in the if statement to run... and if Calculation2 is desired, for the segue in the else if statement to occur. Instead, no matter which button is pressed, the first part of the if statement happens, regardless of if Calculation2 was selected previously.
This problem is about passing data from one view controller to another view controller. To pass data from one view controller to
another view controller you can use the methods of segue
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { }
Usage:
Add Extension to your first view controller i.e to your lightViewController
extension lightViewController {
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "goToDarkButtonVC") {
let destVC = segue.destinationViewController as! darkViewController
destVC. findCalc = sender as! Bool
}
}
#IBAction func lightButtonPressed(_ sender: UIButton) {
if sender.tag == 1 && lightViewPromptIndex == 1 {
desiredGpaText = textfield.text!
// In the sender set the value as per your need....
performSegue(withIdentifier: "goToDarkButtonVC", sender: true)
} else if sender.tag == 2 && lightViewPromptIndex == 1 {
// In the sender set the value as per your need....
performSegue(withIdentifier: "goToDarkButtonVC", sender: true)
}
}
}
In your second view controller access the value just like this :
class darkViewController : UIViewController {
var findCalc = false
#IBAction func darkButtonPressed(_ sender: Any) {
if aboveTopPromptIndex == 1 && self.findCalc1 == true {
//TODO: add your handling code here....
}
}
And that's how you can easily achieve your requirement.
Creating a new object lightViewObject() will create a new memory block and it will not contain the values stored in the previous viewController
Use Prepare for a segue to pass data from one view controller to another
class lightViewController : UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "goToDarkButtonVC") {
let destVC = segue.destinationViewController as! darkViewController
destVC.findCalc1 = true // change the value here
}
}
#IBAction func lightButtonPressed(_ sender: UIButton) {
if sender.tag == 1 && lightViewPromptIndex == 1 {
desiredGpaText = textfield.text!
performSegue(withIdentifier: "goToDarkButtonVC", sender: self)
} else if sender.tag == 2 && lightViewPromptIndex == 1 {
performSegue(withIdentifier: "goToDarkButtonVC", sender: self)
}
}
}
Then use the value in darkViewController
class darkViewController : UIViewController {
var findCalc1:Bool = false
#IBAction func darkButtonPressed(_ sender: Any) {
if aboveTopPromptIndex == 1 && self.findCalc1 == true {
//Your Code here
}
}

if nameTextField.text!.isEmpty not working?

Im trying to check if a textFieldis empty, and if it is a popup should show:
func missingText (title: String, message: String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
#IBAction func registerButton(_ sender: UIButton) {
//Display errormsg for missing entry
if nameTextField.text!.isEmpty
{
missingText(title: "Error", message: "Missing name")
}
}
Nothing is happening when the textfield is empty. I (think) I have the exact same code in another app, and that's working fine.. What am I missing?
The nameTextFieldis hooked up.
I had a similar problem once, It turned out that instead of using the placeholder for description for the textfield, I used the Text. Both are located in Attributes inspector for the textField. So, if u use the Textfor description, the textField will never be empty.
I guess textfield text is nil. so that it may not be calling. try with below code
#IBAction func registerButton(_ sender: UIButton) {
guard let text = textField.text, text != "" else{
missingText(title: "Error", message: "Missing name")
return
}
// do stuff with text,
}
u can try this one this might will help you . nametextfield.text , !text.empty

UIAlertController pushes navigation bar item

UIAlewrtController pushes the button in my navigation controller down (see image)
Sequence of execution:
on push + the alert controller is activated
on selecting "Take an Action" or "Request an Action" the view controller ActionDetialsVC is activated.
on showing ActionDetialsVC
on back the ActionDetialsVC is closed
The iitial controlers BACK arrow moved
When putting breakpoints on:
self.present (alert, animated: true, completion: nil)
the first Swift instruction in the 2 alert handlers
The strange navigation back button behavior is visible between these breakpoints.
The issue ONLY occurs when introducing Alert Controllers in my views !!!!!
Thank you for your help
Image of the issue:
The code:
func addPressed(_ sender: Any) {
let alert = UIAlertController (title: "Add an Action", message: nil, preferredStyle: UIAlertControllerStyle.alert)
let request = UIAlertAction (title: actionType.Request.Str(), style: UIAlertActionStyle.default, handler: {
action in
self.actionTypeTemp = actionType.Request.Str()
self.performSegue(withIdentifier: "segueActionDetailsVC", sender: nil)
} )
let take = UIAlertAction (title: actionType.Take.Str(), style: UIAlertActionStyle.default, handler: {
action in
self.actionTypeTemp = actionType.Take.Str()
self.performSegue(withIdentifier: "segueActionDetailsVC", sender: nil)
} )
let done = UIAlertAction (title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil )
alert.addAction(request)
alert.addAction(take)
alert.addAction(done)
self.present (alert, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueActionDetailsVC" {
if let destination = segue.destination as? ActionDetailsVC {
if let action = sender as? PActions {
destination.actionToEdit = action
}
else {
if actionTypeTemp == actionType.Request.Str() {
destination.relatedContact = self.contact
destination.title = actionType.Request.Str()
}
else {
destination.relatedContact = self.contact
destination.title = actionType.Take.Str()
}
}
}
}
}

calling IBAction button inside IBAction?

I got this IBAction that shuffles a pack of cards randomly
#IBAction func playRoundTapped(sender: UIButton) {
cardNamesArray = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(cardNamesArray) as! [String]
cardNamesArray2 = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(cardNamesArray2) as! [String]
let firstCardString:String = self.cardNamesArray[0]
self.FirstCardImageView.image = UIImage(named: firstCardString)
let SecondCardString:String = self.cardNamesArray2[1]
self.SecondCardImageView.image = UIImage(named: SecondCardString)
}
...and this part of the code scores a point when the cards match, however when they macth I need to it to shuffle again. Can I use IBAction playRoundTapped inside IBAction snapButtonTapped?
#IBAction func SnapButtonTapped(sender: UIButton) {
if firstRandomNumber == SecondRandomNumber {
print("index match")
self.playerScore += 1
self.playerScoreLabel.text = String(self.playerScore)
cardNamesArray.removeAtIndex(firstRandomNumber)
cardNamesArray2.removeAtIndex(SecondRandomNumber)
if cardNamesArray.count == 0 && cardNamesArray2.count == 0{
print("user won")
//alert box
let alert = UIAlertController(title:"Level completed", message: "Your score is \(playerScore)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title:"next level", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated:true, completion:nil)
}
}
Yes you can. An IBAction is just a method with a specific signature and a tag that tells Interface Builder it can be connected to controls. You are free to call it yourself.