I'm trying to implement one simple thing - to switch the string value by switching UISwitch.
But, I can get, what is wrong
func switchIsChanged(interestedIn: UISwitch) {
if interestedIn.on == true {
print("UISwitch is ON")
} else {
print("UISwitch is OFF")
}
}
if self.Gender.text == "male" {
switchIsChanged(self.interestedIn)
}
I can show the whole code if necessary. I just taking data from Facebook, understand the gender if user, and the set the value interestedIn depending on his or her gender.
import UIKit
import FBSDKShareKit
import FirebaseDatabase
import FirebaseAuth
import Firebase
class Settings: UIViewController {
#IBOutlet weak var UserImage: UIImageView!
#IBOutlet weak var UserName: UILabel!
#IBOutlet weak var UserSurname: UILabel!
#IBOutlet weak var Gender: UILabel!
#IBOutlet weak var interestedIn: UISwitch!
#IBOutlet weak var GenderofInsterest: UILabel!
var pictureURL : String?
var interest = ""
override func viewDidLoad() {
super.viewDidLoad()
let paramets = ["fields": "email, first_name, last_name, picture.type(large), gender"]
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: paramets)
graphRequest.startWithCompletionHandler({
(connection, result, error) -> Void in
if error != nil {
print (error)
}
if let first_name = result["first_name"] as? String {
self.UserName.text = first_name
}
if let last_name = result["last_name"] as? String {
self.UserSurname.text = last_name
}
if let picture = result["picture"] as? NSDictionary, data = picture["data"] as? NSDictionary, pictureUrl = data["url"] as? String {
self.pictureURL = pictureUrl
let fbUrl = NSURL(string: pictureUrl)
if let picData = NSData(contentsOfURL: fbUrl!) {
self.UserImage.image = UIImage(data: picData)
}
}
if let gender = result["gender"] as? String {
self.Gender.text = gender
}
let people = ProfileClass()
people.profileName = self.UserName.text
people.profileGender = self.Gender.text
people.profileSurname = self.UserSurname.text
people.profilePhotoUrl = self.pictureURL
people.SaveUser()
func switchIsChanged(interestedIn: UISwitch) {
if interestedIn.on == true {
print("UISwitch is ON")
} else {
print("UISwitch is OFF")
}
}
if self.Gender.text == "male" {
switchIsChanged(self.interestedIn)
}
})
}}
As #ILideTau mentioned above, you should not directly work with UISwitch states, instead of that, just create a Bool variable, that will hold your switch state, and update UI when you change its state in didSet { } closure:
#IBOutlet weak var interestedInSwitch: UISwitch!
var interstedInState: Bool = false {
didSet {
interestedInSwitch.on = interstedInState
}
}
func updateInterstedInState(newValue: Bool) {
interstedInState = newValue
}
Related
I am using MySQL and PHP to download a restaurants menu but the user of the app should be able to add a certain amount to which item from the menu they want. Currently I am using a stepper to indicate the amount and adding that amount to a UserDefaults key which gets called when the menu is downloaded again.
This makes me have to download the menu again when I go to another viewController which sums up the order but I can't seem to filter out only them items which do have an amount.
What is a better way to add that amount to the downloaded data and how can I filter these items in my cart ViewController to only show and use the items which have an amount.
My current downloadModel, MenuModel, cellViewController (for the menu tableview) look like this:
MenuDownload.swift:
import UIKit
protocol MenuDownloadProtocol: class {
func productsDownloaded(products: NSArray)
}
class MenuDownload: NSObject {
//properties
weak var delegate: MenuDownloadProtocol!
func downloadProducts() {
let urlPath = "http://server.com/download.php" // Fake URL obviously
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
print("Menu downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let products = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let restomenu = MenuModel()
//the following insures none of the JsonElement values are nil through optional binding
if let product = jsonElement["product"] as? String,
let price = jsonElement["price"] as? String,
let info = jsonElement["info"] as? String,
let imageurl = jsonElement["imageurl"] as? String
{
let productandprice = product + " " + "€" + price
let quantityy = UserDefaults.standard.object(forKey: productandprice) as? String
restomenu.product = product
restomenu.price = price
restomenu.info = info
restomenu.imageurl = imageurl
restomenu.quantity = quantityy
}
products.add(restomenu)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.productsDownloaded(products: products)
})
}
}
extension String {
func chopPrefix(_ count: Int = 1) -> String {
return substring(from: index(startIndex, offsetBy: count))
}
func chopSuffix(_ count: Int = 1) -> String {
return substring(to: index(endIndex, offsetBy: -count))
}
}
MenuModel.swift:
import UIKit
class MenuModel: NSObject {
//properties
var product: String?
var price: String?
var info: String?
var imageurl: String?
var quantity: String?
//empty constructor
override init()
{
}
init(product: String, price: String, info: String, imageurl: String, quantity: String) {
self.product = product
self.price = price
self.info = info
self.imageurl = imageurl
self.quantity = quantity
}
//prints object's current state
override var description: String {
return "product: \(String(describing: product)), price: \(String(describing: price)), info: \(String(describing: info)), imageurl: \(String(describing: imageurl)), quantity: \(String(describing: quantity))"
}
}
tableViewCell.swift:
import UIKit
class productTableViewCell: UITableViewCell {
#IBOutlet weak var productLabel: UILabel!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var cellView: UIView!
#IBOutlet weak var orderCount: UILabel!
#IBOutlet weak var stepper: UIStepper!
var amount: String?
#IBAction func stepperValueChanged(_ sender: UIStepper) {
amount = Int(sender.value).description
orderCount.text = amount
// let defaultkey = String(productLabel.text!)
UserDefaults.standard.setValue(amount, forKey: productLabel.text!)
if amount == "0"
{
orderCount.isHidden = true
UserDefaults.standard.removeObject(forKey: productLabel.text!)
}
else
{
orderCount.isHidden = false
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
EDIT: after trying filtering options and many different ways I still haven't found how to fix this. I think I'm overthinking it too much.
I have made an sign up and also login and it works! but now I want to edit the data in the Firebase. Can anyone help me how to do it? Thanks you
Here the Sign Up View Controller
import UIKit
import FirebaseAuth
import FirebaseFirestore
class SignupViewController: UIViewController {
#IBOutlet weak var FirstNameTextfield: UITextField!
#IBOutlet weak var LastNameTextfield: UITextField!
#IBOutlet weak var EmailTextField: UITextField!
#IBOutlet weak var PasswordTextfield: UITextField!
#IBOutlet weak var SignUpButton: UIButton!
#IBOutlet weak var ErrorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
}
func setUpElements(){
ErrorLabel.alpha = 0
}
func validateFields()->String? {
//check that all the fields are fill
if FirstNameTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || LastNameTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || EmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || PasswordTextfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""
{
return "Please fill up all the Fields"
}
//check the password if the password is secure
let cleanedPassword = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword) == false{
return "Please enter at least 8 characters, with a number and characteristic symbol"
}
return nil
}
#IBAction func SignUpTap(_ sender: Any) {
let error = validateFields()
if error != nil{
showError(message: error!)
}
else {
let FirstName = FirstNameTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let LastName = LastNameTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Email = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Password = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().createUser(withEmail: Email, password: Password) { (result, err) in
if err != nil{
self.showError(message: "Error creating the user")
}
else {
let db = Firestore.firestore()
db.collection("users").addDocument(data:["FirstName":FirstName, "LastName":LastName, "uid": result!.user.uid]) { (Error) in
if error != nil{
self.showError(message: "Cannot saving user data" )
}
}
self.transitionToHomePage()
}
}
}
}
func showError( message:String){
ErrorLabel.text = message
ErrorLabel.alpha = 1
}
func transitionToHomePage(){
let TabHomeViewController = storyboard?.instantiateViewController(identifier: Constrants.Storyboard.TabHomeViewController) as? TabHomeViewController
view.window?.rootViewController = TabHomeViewController
view.window?.makeKeyAndVisible()
}
}
Here my login VC
#IBAction func LoginTap(_ sender: Any) {
let Email = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Password = PasswordTextfield.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().signIn(withEmail: Email, password: Password) { (result, error) in
if error != nil{
self.ErrorLabel.text = error!.localizedDescription
self.ErrorLabel.alpha = 1
}
else{
let TabHomeViewController = self.storyboard?.instantiateViewController(identifier: Constrants.Storyboard.TabHomeViewController) as? UITabBarController
self.view.window?.rootViewController = TabHomeViewController
self.view.window?.makeKeyAndVisible()
}
And here my Account View Controller
import UIKit
import FirebaseAuth
import FirebaseFirestore
import Firebase
class AccountViewController: UIViewController {
#IBOutlet weak var FNameTextField: UITextField!
#IBOutlet weak var LNameTextField: UITextField!
#IBOutlet weak var EmailTextField: UITextField!
#IBOutlet weak var PasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func logoutbutton(_ sender: Any) {
do{
try Auth.auth().signOut()
performSegue(withIdentifier: "signout", sender: nil)
}
catch{
print(error)
}
}
}
You can use this function:
func updateFirestoreUserProfile(uid: String, data: [String:Any]) {
Firestore.firestore().collection("users").document(uid).updateData(data) { err in
if let err = err {
print("Error updating document: \(err) ")
}
else {
print("Document successfully updated")
}
}
}
You can use the function like this:
let data = [
"FirstName": name,
"LastName": surname
]
updateFirestoreUserProfile(uid: user.uid, data: data)
Function moveToHome gives error when stating the viewcontroller class. Use of undeclared type 'HomeViewController'. I set the class of the view controller to HomeViewController but it is not being recognized.
import Foundation
import UIKit
import Firebase
import SwiftKeychainWrapper
import FirebaseAuth
import FirebaseFirestore
class SignUpEmail: UIViewController {
#IBOutlet weak var Email: UITextField!
#IBOutlet weak var Password: UITextField!
#IBOutlet weak var Firstname: UITextField!
#IBOutlet weak var Lastname: UITextField!
#IBOutlet weak var City: UITextField!
#IBOutlet weak var Street: UITextField!
#IBOutlet weak var Gender: UITextField!
#IBOutlet weak var SignupButton: UIButton!
#IBOutlet weak var errorLAbel: UILabel!
var userUid: String!
override func viewDidLoad() {
super.viewDidLoad()
SignupButton.layer.cornerRadius = 15
errorLAbel.alpha = 0
}
// Check fields, If everything is correct returns Nil otherwise returns error.
func validateFields() -> String? {
if Email.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
Password.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
Firstname.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
Lastname.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
City.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
Street.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
Gender.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all fields."
}
// Check if password is secure
let cleanedPassword = Password.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword) == false {
// Password isn't secure enough
return "Please make sure your password is at least 8 characters, contains a special character and a number."
}
return nil
}
#IBAction func SignupTapped(_ sender: Any) {
//Validate
let error = validateFields()
if error != nil {
// Something is wrong with the fields
showError(error!)
}
else {
// Create User
// Create clean versions of data
let lastname = Lastname.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let firstname = Firstname.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let email = Email.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = Password.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let city = City.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let street = Street.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let gender = Gender.text!.trimmingCharacters(in: .whitespacesAndNewlines)
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
//check for errors
if err != nil {
// There was an error creating the user
self.showError("Error Creating User")
}
else {
//User was creating successfully now store
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["firstname":firstname, "lastname":lastname, "City": city, "Street": street, "Gender":gender, "uid": result!.user.uid]) { (Error) in
if error != nil {
self.showError("Error saving user data")
}
}
// Move to homescreen
self.moveToHome()
}
}
}
}
func showError(_ message:String) {
errorLAbel.text = message
errorLAbel.alpha = 1
}
func moveToHome() {
let storyboard = UIStoryboard(name: "Main.storyboard", bundle: nil)
let homeViewController = storyboard?.instantiateViewController(identifier: "HomeVC") as? HomeViewController //This part gives error
view.window?.rootViewController = homeViewController
view.window?.makeKeyAndVisible()
}
}
(Ignore had to add extra text to be able to post)
try:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
uses "Main" instead of "Main.storyboard"
and make sure that the StoryboadID has been set
I've created a SignUp page (ViewController) and on gender selection I'm using a UISegmentedControl for "male", "female", "indifferent". But how can I get the value from the UISegmentedControl and put in a dictionary? I'm using a custom Dictionary<String, String> = [:] for signup but the UISegmentedControl is not a string (obviously) and I get the error:
Cannot assign value of type 'UISegmentedControl' to type 'String'
How can I convert the result of UISegmentedControl to receive those values?
import UIKit
import FirebaseAuth
import Firebase
class SignUpViewController: UIViewController{
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var birthdayField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var confirmpasswordField: UITextField!
#IBOutlet weak var instagramuserField: UITextField!
#IBOutlet weak var generoSegmentControl: UISegmentedControl!
#IBOutlet weak var DatePickerDate: UITextField!
#IBOutlet weak var signupOutlet: UIButton!
#IBAction func signupAction(_ sender: Any) {
if let name = self.nameField.text {
if let email = self.emailField.text {
if let birthday = self.birthdayField.text {
if let password = self.passwordField.text {
if let confirmpassword = self.confirmpasswordField.text {
if let instagramuser = self.instagramuserField.text {
if let gender = self.generoSegmentControl {
if password == confirmpassword {
print("Senhas iguais, podemos seguir")
}else {
print("As senhas precisam ser iguais")
}
self.auth.createUser(withEmail: email, password: password) { (user, error) in
if error == nil {
var user: Dictionary<String, String> = [:]
user["nome"] = name
user["email"] = email
user["nascimento"] = birthday
user["instagram"] = instagramuser
user["genero"] = gender
//Encoding email for Base 64
let key = Base64().encodingStringBase64(text: email)
let users = self.database.reference().child("usuarios")
users.child(key).setValue(user)
print("Sucesso ao cadastrar usuário!")
}else{
print("Erro ao cadastrar usuário, tente novamente!")
}
}
}else {
print("Escolha seu genero")
}
}else{
print("O campo usuário do instagram esta vazio")
}
}else{
print("As senhas não conferem")
}
}else{
print("Digite uma senha")
}
}else{
print("Digite a data do seu nascimento")
}
}else{
print("Digite seu e-mail")
}
}else{
print("Digite seu nome")
}
}
#IBAction func generoAction(_ sender: Any) {
let genIndex = generoSegmentControl.selectedSegmentIndex
switch genIndex {
case 0:
print("Homem")
case 1:
print("Mulher")
case 2:
print("Indiferente")
default:
print("Nada selecionado")
}
}
}
You get the segmentedControl in your code, but not it's selectedSegmentIndex property. Then after receiving the selectedSegmentIndex, you should get the title for that index from control. Update your code with following:
if let gender = self.generoSegmentControl {
Either change it to:
let genderIndex = self.generoSegmentControl.selectedSegmentIndex
if let gender = self.generoSegmentControl.titleForSegment(at: genderIndex) {
}
OR change the way you update dictionary:
let index = gender.selectedSegmentIndex
if let segmentTitle = gender.titleForSegment(at: index) {
user["nome"] = name
user["email"] = email
user["nascimento"] = birthday
user["instagram"] = instagramuser
user["genero"] = segmentTitle
}
Usually Alamofire working nice with simple urls like:
"http://somesite.com/folder/file.json"
But when I use:
"http://somesite.com/folder/(jsonName.text).json
it always give me a nil... jsonName is a TextField as well...
That's the whole Controller:
import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
import CoreData
typealias CompletionHandler = (obj:AnyObject?, error:Bool?) -> Void
class LoginViewController: UIViewController, UITabBarControllerDelegate, UITextFieldDelegate, NSURLConnectionDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
#IBOutlet weak var wePrepareQuestLabel: UILabel!
#IBOutlet weak var downQuestProgres: UIActivityIndicatorView!
#IBOutlet weak var doNotCloseAppLabel: UILabel!
#IBOutlet weak var loginBgImage: UIImageView!
#IBOutlet weak var EmptyCodeError: UILabel!
#IBOutlet weak var loginTabBarItem: UITabBarItem!
#IBOutlet weak var QuestCodeTextField: UITextField!
#IBOutlet weak var loginTextFieldImage: UIImageView!
#IBOutlet weak var downloaded: UIButton!
#IBOutlet weak var createQuestButton: UIButton!
#IBAction func createQuest(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("WebViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
let Path: String = ""
#IBAction func QuestFetchButton(button: UIButton) {
if QuestCodeTextField.text.isEmpty {
EmptyCodeError.hidden = false
}
else if IJReachability.isConnectedToNetwork() {
}
else
{
QuestCodeTextField.hidden = true
button.hidden = true
EmptyCodeError.hidden = true
createQuestButton.hidden = true
doNotCloseAppLabel.hidden = false
wePrepareQuestLabel.hidden = false
loginTextFieldImage.hidden = true
downQuestProgres.hidden = false
self.downloaded.hidden = false
// questDownloadSaveJSON()
var objThisVC = LoginViewController()
objThisVC.callAndGetResponse { (obj, error) -> Void in
if (obj != nil) {
self.setUpDataInCoreData(obj)
print("ALL DIE")
self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
}
else {
println("Response nil!!")
}
}
}
}
var file:NSFileHandle?
var pathURL: NSURL
{
let folder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let path = folder.stringByAppendingPathComponent("\(QuestCodeTextField.text).json")
let url = NSURL(fileURLWithPath: path)
return url!
}
var code: String = ""
override func viewDidLoad() {
super.viewDidLoad()
QuestCodeTextField.text = code
self.QuestCodeTextField.delegate = self;
}
func setUpDataInCoreData(obj:AnyObject?){
println("Web Serviece Response \(obj)")
let dirEvent = obj as! NSDictionary
var aryEvent = dirEvent.valueForKey("events") as! NSArray
var indexEvent : Int = 0;
for (dirContent) in aryEvent
{
// Create Event Instance
var newItem: Events = NSEntityDescription.insertNewObjectForEntityForName("Events", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Events
newItem.title = dirContent.valueForKey("title") as! String
newItem.indexID = String(indexEvent++) as String
println(newItem.title)
println(newItem.indexID)
var indexContent : Int = 0;
var aryContent = dirContent.valueForKey("content") as! NSArray
for (dirContentDetail) in aryContent{
var contentEntity: Content = NSEntityDescription.insertNewObjectForEntityForName("Content", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Content
contentEntity.content_type = dirContentDetail.valueForKey("content_type") as! String
contentEntity.visible = dirContentDetail.valueForKey("visible") as! Bool
contentEntity.indexID = String(indexContent++) as String
println(contentEntity.content_type)
println(contentEntity.visible)
if contentEntity.content_type == "text"{
contentEntity.data_type = dirContentDetail.valueForKey("data") as! String
}
else if contentEntity.content_type == "image" || contentEntity.content_type == "audio" || contentEntity.content_type == "video" || contentEntity.content_type == "choice" {
contentEntity.data_type = ""
if (dirContentDetail.valueForKey("data") != nil && dirContentDetail.valueForKey("data")?.count>0 )
{
var indexImage : Int = 0;
var aryDTImages = dirContentDetail.valueForKey("data") as! NSArray
if aryDTImages.count > 0 {
for strContentDetail in aryDTImages as! [String]{
var objDtImg : DataTypeImage = NSEntityDescription.insertNewObjectForEntityForName("DataTypeImage", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! DataTypeImage
var strURL : NSString = NSString(string: strContentDetail)
objDtImg.urlString = strURL as String
objDtImg.indexID = String(indexImage++) as String
objDtImg.dtImages = contentEntity
// her have to set image to content
contentEntity.content = newItem
}
}
}
}
// here have to set entity to content
contentEntity.content=newItem
}// this is the end of content for loop
}// end of aryEvent
// here to save statement
self.appDelegate.cdh.saveContext(self.appDelegate.cdh.backgroundContext!)
// self.table.reloadData()
}
func callAndGetResponse(complitionHandler : CompletionHandler){
complitionHandler(obj: nil, error: true)
Alamofire.request(.GET, "http://g57732cr.bget.ru/\(QuestCodeTextField.text).json").responseJSON() {
(_, _, data, error) in
if error == nil {
complitionHandler(obj: data, error: false)
}
else{
complitionHandler(obj: nil, error: true)
self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
}
// Fetch all data from Core Data
//self.fetchAllData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Hide keyboard by tap on the rest of the view
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
view.endEditing(true)
}
//ReturnButton hides keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "QuestsListViewController"){
var destination = segue.destinationViewController as! UINavigationController
let VC = destination.topViewController as! QuestListViewController
VC.questCode = self.QuestCodeTextField.text
}
}
}