I got the tutorial from this site: http://jamesleist.com/ios-swift-tutorial-stop-segue-show-alert-text-box-empty/
This is my current code. It's just not working, which causes the app to crash because if any of the fields are empty, the next ViewController crashes.
import Foundation
import UIKit
import Darwin
class View3on3 : UIViewController, UITextFieldDelegate {
#IBOutlet weak var APTeams: UITextField!
#IBOutlet weak var APRounds: UITextField!
#IBOutlet weak var APBreakers: UITextField!
var AP1: String = String()
var AP2: String = String()
var AP3: String = String()
override func viewDidLoad()
{
super.viewDidLoad()
initializeTextFields()
}
func initializeTextFields()
{
APTeams.delegate = self
APTeams.keyboardType = UIKeyboardType.NumberPad
APRounds.delegate = self
APRounds.keyboardType = UIKeyboardType.NumberPad
APBreakers.delegate = self
APBreakers.keyboardType = UIKeyboardType.NumberPad
}
#IBAction func userTappedBackground(sender: AnyObject)
{
view.endEditing(true)
}
override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
if identifier == "segueTest" {
if (APTeams.text!.isEmpty) {
let alert = UIAlertView()
alert.title = "No Text"
alert.message = "Please Enter Text In The Box"
alert.addButtonWithTitle("Ok")
alert.show()
return false
}
else {
return true
}
}
// by default, transition
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "segueTest"){
var passs = segue.destinationViewController as! View3on3Results
passs.AP1 = APTeams.text!
passs.AP2 = APRounds.text!
passs.AP3 = APBreakers.text!
}
}
}
I tried looking at other questions on SO, but the solutions all threw errors. I think this is due to Swift updating to 2.0. I could be wrong- very new to this.
I hope it may be because of AlertView. In swift 2.0 UIAlertView is replaced by UIAlertController:
let alertController: UIAlertController = UIAlertController(title: "Hello", message: "Are you sure?", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(okAction)
presentViewController(alertController, animated: true, completion: nil)
Replace your UIAlertView with UIAlertViewController using the above code.
Edited:
Also make the IBOutlet optionals:
#IBOutlet weak var APTeams: UITextField?
#IBOutlet weak var APRounds: UITextField?
#IBOutlet weak var APBreakers: UITextField?
I think you should call segue manually using performSegueWithIdentifier
if the textfield is not empty and if it is then show alert
Your code might look like [may be on button click when you are submitting your data or trying to segue Or put this code inside viewDidLoad after initializeTextFields()]
if(APTeams.text!.isEmpty){
// your code for showing alert. You can use UIAlertController if UIAlertView is not working.
}
else
{
self.performSegueWithIdentifier("segueTest",sender: View3on3Results.self)
}
And you dont need shouldPerformSegueWithIdentifier if I'm not wrong.
Solved! This was the code that worked. Thank you to #SohilRMemon and #FrequencyMatched for helping me put this together.
Code here:
import Foundation
import UIKit
import Darwin
class View3on3 : UIViewController, UITextFieldDelegate {
#IBOutlet weak var APTeams: UITextField!
#IBOutlet weak var APRounds: UITextField!
#IBOutlet weak var APBreakers: UITextField!
var AP1: String = String()
var AP2: String = String()
var AP3: String = String()
override func viewDidLoad()
{
super.viewDidLoad()
initializeTextFields()
}
func initializeTextFields()
{
APTeams.delegate = self
APTeams.keyboardType = UIKeyboardType.NumberPad
APRounds.delegate = self
APRounds.keyboardType = UIKeyboardType.NumberPad
APBreakers.delegate = self
APBreakers.keyboardType = UIKeyboardType.NumberPad
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (APTeams.text!.isEmpty || APRounds.text!.isEmpty || APBreakers.text!.isEmpty)
{
let alertController: UIAlertController = UIAlertController(title: "Hello", message: "Are you sure?", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(okAction)
presentViewController(alertController, animated: true, completion: nil)
}
else
{
let DestViewController : View3on3Results = segue.destinationViewController as! View3on3Results
DestViewController.AP1 = APTeams.text!
DestViewController.AP2 = APRounds.text!
DestViewController.AP3 = APBreakers.text!
//self.performSegueWithIdentifier("segueTest",sender: View3on3Results.self)//
}
}
}
Related
Login page doesn't really check for if user is stored in core data and will just go ahead with the segue. It should login only if user is registered in core data else will input error and to go register but register seems to work correctly tho I followed some guides online
I have attached the code please check and give me some suggestion to achieve my task
LoginVC
import UIKit
import CoreData
class LoginVC: UIViewController {
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
var credits = 200.0
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
fetchData()
}
#IBAction func login(_ sender: Any) {
for acc in userList {
if acc.username == username.text && acc.password == password.text {
currentUser = username.text!
try! context.save()
//performSegue(withIdentifier: "DisplayShop1", sender: nil)
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let next = storyBoard.instantiateViewController(identifier: "DisplayShop1") as! ListingShopVC
next.modalPresentationStyle = .fullScreen
self.present(next, animated: true, completion: nil)
}
else if username.text != acc.username || password.text != acc.password || password.text == "" || username.text == "" {
let alert = UIAlertController(title: "Alert", message: "Please enter the correct credentials", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "hellothere" {
let ve = segue.destination as! ListingShopVC
ve.creditsss = credits
}
}
func fetchData(){
userList = try! context.fetch(User.fetchRequest())
}
}
RegisterVC
import UIKit
import CoreData
class RegisterVC: UIViewController {
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var userList: String = ""
#IBOutlet weak var username: UITextField!
#IBOutlet weak var cpassword: UITextField!
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func register(_ sender: Any) {
if username.text != ""{
if password.text != "" {
if password.text == cpassword.text {
let newu = User(context: context)
newu.username = username.text
newu.password = password.text
newu.credit = 200.0
try! context.save()
self.navigationController?.popViewController(animated: true)
}
else {
let alert = UIAlertController(title: "Alert", message: "Please enter values correctly", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)*/
}
}
}
}
I have called function and It isn't still displaying the code right I have been receiving and error Use of local variable 'displayAlert' before its declaration
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
// I have also switched the #IBAction to function so the code actually run better any suggestions to fix this
#IBOutlet weak var dropoffLabel: UILabel!
#IBOutlet weak var pickupLabel: UILabel!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var emailTextfield: UITextField!
#IBOutlet weak var pickupDropoffSwitch: UISwitch!
#IBOutlet weak var buttomButton: UIButton!
#IBOutlet weak var topButton: UIButton!
var signUpMode = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func topTapped(_ sender: Any) {
if emailTextfield.text == "" || passwordTextField.text == "" {
code error coming from here ----> displayAlert(title: "Missing Information", message: "You must provide both a email and password")
} else {
if let email = emailTextfield.text {
if let password = passwordTextField.text {
if signUpMode {
// SIGN UP
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
displayAlert(title: "Error", message: error!.localizedDescription)
} else {
print("Sign Up Success")
}
})
} else {
// LOG IN
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
displayAlert(title: "Error", message: error!.localizedDescription)
} else {
print("Sign Up Success")
}
})
}
}
}
}
------> I believe if I am doing it correctly called the function here func displayAlert(title:String, message:String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
//there is no other issue besides the code not understanding the the function I have labeled
//Also I have ran the code before and the alert would pop up but now it is not allowing the
func buttomTapped(_ sender: Any) {
if signUpMode {
topButton.setTitle("Log In", for: .normal)
buttomButton.setTitle("Switch to Sign Up", for: .normal)
pickupLabel.isHidden = true
dropoffLabel.isHidden = true
pickupDropoffSwitch.isHidden = true
signUpMode = false
} else {
topButton.setTitle("Sign Up", for: .normal)
buttomButton.setTitle("Switch to Log In", for: .normal)
pickupLabel.isHidden = false
dropoffLabel.isHidden = false
pickupDropoffSwitch.isHidden = false
signUpMode = true
}
}
}
}
You have incorrectly defined your displayAlert func inside the topTapped func.
You need to move it outside so it is on the class level
#IBAction func topTapped(_ sender: Any) {
//code here
}
func displayAlert(title:String, message:String) {
//
}
In an app I am currently writing, I have a string named 'User' which stores the user's name for a game. The value of the string, when printed anywhere else in the Swift file, prints the value that I have set, as an optional.
If I try to use this string as the title of an action sheet action, the string is automatically set to nil, which I can see as both the title of the action and which is printed when I ask it to print(user).
If anyone could shed some light as to why this is happening, or how to prevent it, that would be great. I have also posted my Swift file below, thanks.
import UIKit
class MainViewController: UIViewController {
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBOutlet weak var firstView: UIView!
#IBOutlet weak var secondView: UIView!
var user:String!
var playerTwo:String!
var playerThree:String!
var playerFour:String!
var playerFive:String!
var playerSix:String!
var userCards = [String]()
override func viewDidLoad() {
super.viewDidLoad()
firstView?.isHidden = false
secondView?.isHidden = true
}
#IBAction func valueDidChange(_ sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex {
case 0:
firstView.isHidden = false
secondView.isHidden = true
case 1:
firstView.isHidden = true
secondView.isHidden = false
default:
break;
}
}
#IBAction func confirm(_ sender: UIButton) {
let alertController = UIAlertController(title: "Action Sheet", message: "What would you like to do?", preferredStyle: .actionSheet)
let userButton = UIAlertAction(title: user /* Here I have tried with putting both 'user', and "\(user)"*/, style: .default, handler: { (action) -> Void in
print("User button tapped")
})
let deleteButton = UIAlertAction(title: "Delete button test", style: .destructive, handler: { (action) -> Void in
print("Delete button tapped")
})
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
print("Cancel button tapped")
})
alertController.addAction(userButton)
alertController.addAction(deleteButton)
alertController.addAction(cancelButton)
self.present(alertController, animated: true, completion: nil)
}
}
The value is passed into the above file directly from this code in another file:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMainController" {
let VC = segue.destination as! MainViewController
VC.user = self.user
if playerTwo != nil {
VC.playerTwo = self.playerTwo
}
if playerThree != nil {
VC.playerThree = self.playerThree
}
if playerFour != nil {
VC.playerFour = self.playerFour
}
if playerFive != nil {
VC.playerFive = self.playerFive
}
if playerSix != nil {
VC.playerSix = self.playerSix
}
}
}
The value is, however, passed through several view controllers, and is initially set here:
if (meTextField.text?.isEmpty)! == false {
let p1 = meTextField.text!
initialPlayersDict["player1"] = "\(p1)"
if errLabelNotBlank {
errorLabel.text = ""
errLabelNotBlank = false
}
}
How can I make a button to retrieve the latest information set
For example, when I write Number: 1
After this write: 2
And: 3
And: 4
I want a button retrieves the last number I write before Number: 4
image
Here is my code
import UIKit
class ViewController: UIViewController {
var actionString : String?
#IBOutlet weak var textfiled: UITextField!
#IBOutlet var lblzerous: UILabel!
#IBOutlet var lbl: UILabel!
#IBOutlet var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func me() {
lbl.text! = lbl.text! + "\n" + textfiled.text! + "\n" + "----"
lbl.numberOfLines = 0
self.lblzerous.text = String(CInt(self.textfiled.text!)! + CInt(self.lblzerous.text!)!)
}
#IBAction func button(sender: AnyObject) {
if textfiled.text! == "" {
let alertController = UIAlertController(title: "Error", message: " write the number ", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "ok", style: .Cancel) { (action) -> Void in
self.actionString = "Cancel"
}
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
return
}
me()
if Int(lblzerous.text!) >= Int("152") {
let alertController = UIAlertController(title: "Gmae Over", message: " ... \(lblzerous.text!)", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "...", style: .Cancel) { (action) -> Void in
self.actionString = "Cancel"
}
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
print("keep going ....!")
}
}
#IBAction func button1(sender: AnyObject) {
// Do SomeCode
}
}
Add an array variable to serve you as a stack from which you revert the changes:
var previousValues: [String] = [String]();
var actionString : String?
#IBOutlet weak var textfiled: UITextField!
#IBOutlet var lblzerous: UILabel!
#IBOutlet var lbl: UILabel!
#IBOutlet var button: UIButton!
Then in me() do:
func me() {
lbl.text! = lbl.text! + "\n" + textfiled.text! + "\n" + "----"
lbl.numberOfLines = 0
self.lblzerous.text = String(CInt(self.textfiled.text!)! + CInt(self.lblzerous.text!)!)
previousValues.append(textField.text ?? "error");
}
Edit: Finally in your retreat button do:
#IBAction func button1(sender: AnyObject) {
if previousValues.count > 0 {
let previousValue = previousValues.removeLast();
lbl.text! = lbl.text! + "\n-" + previousValue + "\n" + "----";
let subtracted = (Int(lblzerous.text!)!) - (Int(previousValue)!);
lblzerous.text = "\(subtracted)"
}
}
Edit2: Give default values to your labels:
override func viewDidLoad() {
super.viewDidLoad()
lblzerous.text = "0";
lbl.text = "0";
}
Good day. I'm facing a weird issue, I'd like to set the right navigation item to Done in my next when I've selected a row. I tried it, and it's worked. But it's breaking however, because the function which implements the doneEditing body, is only in the next view controller, any help will be really appreciated. This is my code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "editContact" {
let indexPath = tableView.indexPathForSelectedRow()
let destinationVC: NewCategoryViewController = segue.destinationViewController as! NewCategoryViewController
let contact:Contact = fetchedResultController.objectAtIndexPath(indexPath!) as! Contact
destinationVC.contact = contact
var rightAddBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneEditing:")
destinationVC.navigationItem.rightBarButtonItem = rightAddBarButtonItem
}
}
and my next view controller is :
import UIKit
import CoreData
class NewCategoryViewController: UIViewController {
// MARK: - Properties
var contact: Contact? = nil
// initialize the core data context:
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// MARK: - Outlets
#IBOutlet weak var imageHolder: UIImageView!
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var phoneField: UITextField!
#IBOutlet weak var categoryField: UITextField!
// MARK: - Actions
#IBAction func savebtn(sender: AnyObject) {
let entity = NSEntityDescription.entityForName("Contact", inManagedObjectContext: context!)
let newContact = Contact(entity: entity!, insertIntoManagedObjectContext: context)
newContact.name = nameField.text
newContact.email = emailField.text
newContact.phone = phoneField.text
//newContact.photo = UIImageJPEGRepresentation(imageHolder.image, 1)
var error: NSError?
context?.save(&error)
if let errorSaving = error {
var alert = UIAlertController(title: "Alert", message: "Couldn't save contact !!!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
nameField.text = ""
emailField.text = ""
phoneField.text = ""
var alert = UIAlertController(title: "Notification", message: "Contact added", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = contact?.name
if contact != nil {
nameField.text = contact?.name
emailField.text = contact?.email
phoneField.text = contact?.phone
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func doneEditing() {
}
}
change target from self to destinationVC.
Use this:
var rightAddBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: destinationVC, action: "doneEditing:")
self should be used when the selector is defined in the same class which makes the call. In this case the selector is in a separate class.
OR
I would suggest you to add the right bar button in the viewDidLoad method of NewCategoryViewController. In which case the code will be:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneEditing:")
AND
implement doneEditing: method as
func doneEditing(sender: UIBarButtonItem) {
}