Hitting Return to save Text Input - xcode

I have a text field on my xcode project, how can I do to save the user input just by hitting return on the keyboard, instead of using a button to save it?
ViewController with the new code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textFieldInput: UITextField!
#IBOutlet weak var iphoneSaveCharName: UIButton!
#IBOutlet weak var charOne: UIButton!
#IBOutlet weak var charTwo: UIButton!
#IBOutlet weak var charThree: UIButton!
#IBOutlet weak var charFour: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #IBAction func iphoneSaveTextInput(sender: UIButton) -> Void{
//
// let textData = textFieldInput.text
// textFieldInput.hidden = true
// iphoneSaveCharName.hidden = true
// }
var savedText: String!
func textFieldShouldReturn(textFieldInput: UITextField) -> Bool {
savedText = textFieldInput.text
println(savedText)
textFieldInput.resignFirstResponder()
return false
}
#IBAction func editText(sender: AnyObject) {
if sender is UILongPressGestureRecognizer &&
sender.state == UIGestureRecognizerState.Began {
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
let button = sender.view as UIButton
if button.tag == 1{
charOne.setTitle(savedText, forState: .Normal)
} else if button.tag == 2{
charTwo.setTitle(savedText, forState: .Normal)
} else if button.tag == 3{
charThree.setTitle(savedText, forState: .Normal)
} else if button.tag == 4{
charFour.setTitle(savedText, forState: .Normal)
}
}
}
}
The editText function is a long press gesture recognizer that checks what button is being long pressed.

Set the view controller as a text field delegate and add the appropriate delegate method.
class viewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField: UITextField!
var savedText: String!
func textFieldShouldReturn(textField: UITextField) -> Bool {
savedText = textField.text
textField.resignFirstResponder()
return false
}
}

Related

swift 4- Save the last data of a text field in a label so that they are displayed when the app is restarted

I have a problem, I want to create a small app in which data in a formula can be charged.
Currently the data from three ViewControllers and one PickerViewController will be given back to the first ViewController.
That works very well too.
Now I want that the data at the start not on "nil" set but have a certain value.
Thereafter, the data entered last should reappear when the app is restarted.
I would like to apologize for my english, it is not my preferred language ...
Here is a part of my code how I wrote it
Main ViewController:
import UIKit
class RecivingViewController: UIViewController, SendDataBack, SendDataBack2, SendDataBack3, SendDataBack4 {
#IBOutlet weak var recivingData: UILabel!
#IBOutlet weak var recivingData2: UILabel!
#IBOutlet weak var recivingData3: UILabel!
#IBOutlet weak var recivingData4: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func userData(data: String) {
recivingData.text = data
}
func userData2(data: String) {
recivingData2.text = data
}
func userData3(data: String) {
recivingData3.text = data
}
func PickerData(data: String){
recivingData4.text = data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "view1" {
let SendingVC: SendingViewController = segue.destination as! SendingViewController
SendingVC.delegate = self
}
if segue.identifier == "view2" {
let SendingVC2: Sending2ViewController = segue.destination as! Sending2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "view3" {
let SendingVC3: Sending3ViewController = segue.destination as! Sending3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "picker" {
let SendingVC4: PickerViewController = segue.destination as! PickerViewController
SendingVC4.delegate = self
}
}
}
one of the other ViewControllers:
import UIKit
protocol SendDataBack {
func userData(data: String)
}
class SendingViewController: UIViewController {
#IBOutlet weak var DataTxt: UITextField!
var delegate: SendDataBack? = nil
#IBAction func done(_ sender: Any) {
if delegate != nil {
if DataTxt.text != nil {
let data = DataTxt.text
delegate?.userData(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
In order to see data after app is restarted you should use user defaults.
For saving data
UserDefaults.standard.set(newValue, forKey: "data")
For loading data in your view controller, if it's first load, when data is nil
UserDefaults.standard.string(forKey: "data")

Change textcolor for UITextField

I am trying to change the textColor.Though I enter the numbers correctly into the textfields,it is working only for "else" condition but not for 'if'. Here is my code.
Can anyone fix this issue. Thanks
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var questionOne: UILabel!
#IBOutlet weak var fieldOne: UITextField! // textFields should be set as labels
#IBOutlet weak var questionTwo: UILabel!
#IBOutlet weak var fieldTwo: UITextField!
#IBOutlet weak var questionThree: UILabel!
#IBOutlet weak var fieldThree: UITextField!
#IBOutlet weak var questionFour: UILabel!
#IBOutlet weak var fieldFour: UITextField!
#IBAction func submitButton(sender: UIButton) {
fieldOneColorChange()
fieldTwoColorChange()
fieldThreeColorChange()
fieldFourColorChange()
}
#IBAction func resetButton(sender: UIButton) {
}
// Text color changes
func fieldOneColorChange() {
if fieldOne == 1 {
questionOne.textColor = UIColor.redColor()
} else {
questionOne.textColor = UIColor.blueColor()
}
}
func fieldTwoColorChange() {
if fieldTwo == 2 {
questionTwo.textColor = UIColor.brownColor()
} else {
questionTwo.textColor = UIColor.redColor()
}
}
func fieldThreeColorChange(){
if fieldThree == 3 {
questionThree.textColor = UIColor.blueColor()
} else {
questionThree.textColor = UIColor.purpleColor()
}
}
func fieldFourColorChange(){
if fieldFour == 4 {
questionFour.textColor = UIColor.blueColor()
} else {
questionFour.textColor = UIColor.redColor()
}
}
Change your if statement like this
if fieldOne.text=="1"
so on for every if statement respectively

Optional() in my text view

For one of my static labels on my main story board, it prints out "Optional("United States"). However, I would like it to print out "United States". So my question is, how do I get rid of the "Optional" part? I've already tried doing:
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
I think the exclamation mark is supposed to "unwrap" some value right? However, even if I do p = placemarks!.first, it prints out "Optional("United States").
Below is the rest of my code just in case you would like some context:
//
// ViewController.swift
// Map Demo Rob 2
//
// Created by Jae Hyun Kim on 8/17/15.
// Copyright © 2015 Jae Hyun Kim. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var latitudeLabel: UILabel!
#IBOutlet weak var longitudeLabel: UILabel!
#IBOutlet weak var courseLabel: UILabel!
#IBOutlet weak var speedLabel: UILabel!
#IBOutlet weak var altitudeLabel: UILabel!
#IBOutlet weak var addressLabel: UILabel!
var manager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let userLocation: CLLocation = locations[0]
self.latitudeLabel.text = "\(userLocation.coordinate.latitude)"
self.longitudeLabel.text = "\(userLocation.coordinate.longitude)"
self.courseLabel.text = "\(userLocation.course)"
self.speedLabel.text = "\(userLocation.speed)"
self.altitudeLabel.text = "\(userLocation.altitude)"
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {(placemarks, error) -> Void in
print(userLocation)
if error != nil {
print(error)
return
}
else {
if let p = placemarks?.first{
self.addressLabel.text = "\(p.country)"
}
}
})
}
}
In
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
p.country is an Optional<String>. You need to unwrap that aswell in order to output only it's content (if it exists).
if let country = placemarks?.first?.country {
self.addressLabel.text = country
}

Trying to unhide UITextView from behind keyboard

I am using the code below to unhide UITextFields. It works great until I try to unhide a UITextView. It crashes with an error of trying to unwrap a nil value. My question is what do I need to implement to make the UITextView unhide like the UITextFields? Or do I need to use something beside a UITextView to allow a paragraph style input?
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField2: UITextField!
#IBOutlet weak var notesInput: UITextView!
#IBOutlet weak var scrollView: UIScrollView!
var activeTextField: UITextField!
// MARK: - View
override func viewDidLoad() {
super.viewDidLoad()
self.textField1.delegate = self
self.textField2.delegate = self
// self.textField3.delegate = self
// self.textField4.delegate = self
// self.textField5.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.registerForKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.unregisterFromKeyboardNotifications()
}
// MARK: - Keyboard
// Call this method somewhere in your view controller setup code.
func registerForKeyboardNotifications() {
let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
center.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
func unregisterFromKeyboardNotifications () {
let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
center.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
// Called when the UIKeyboardDidShowNotification is sent.
func keyboardWasShown (notification: NSNotification) {
let info : NSDictionary = notification.userInfo!
let kbSize = (info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue() as CGRect!).size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
var aRect = self.view.frame
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, self.activeTextField.frame.origin) ) {
self.scrollView.scrollRectToVisible(self.activeTextField.frame, animated: true)
}
}
// Called when the UIKeyboardWillHideNotification is sent
func keyboardWillBeHidden (notification: NSNotification) {
let contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
// MARK: - Text Field
func textFieldDidBeginEditing(textField: UITextField) {
self.activeTextField = textField
}
func textFieldDidEndEditing(textField: UITextField) {
self.activeTextField = nil
}

Pass data via segue between 2 view controllers and update labels

I am trying to pass var projectNumber from ViewController to Project1ViewController via segue and save it as var projectNum. Then use projectNum to update the labels in Project1ViewController. The segue and action/outlets are all set up. The app runs fluently (no errors), however, projectNum in Project1ViewController is not getting the projectNumber value and making it projectNum.
How do I pass the projectNumber value from ViewController to Project1ViewController and save it in projectNum? I've seen tutorials that describe similar actions being performed via delegates, but I'm unsure if delegates are applicable to my question. Any feedback helps.
ViewController
import UIKit
class ViewController: UIViewController{
var projectNumber:String = ""
#IBOutlet var projectButton1 : UIButton!
#IBOutlet var projectButton2 : UIButton!
#IBOutlet var projectButton3 : UIButton!
#IBOutlet var projectButton4 : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func updateLabels(sender: UIButton!) {
projectNumber = String(sender.tag)
println(projectNumber)
sender.setTitle(String(projectNumber), forState: UIControlState.Normal)
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
//if user presses Project 3921 button
if segue.identifier == "Project3921Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//if user presses Project 3922 button
else if segue.identifier == "Project3922Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//if user presses Project 3923 button
else if segue.identifier == "Project3923Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//otherwise user presses Project 3924 button
else if segue.identifier == "Project3924Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
}
}
}
Project1ViewController
import UIKit
class Project1ViewController: UIViewController {
var projectNum:String!
#IBOutlet var projectNumLabel: UILabel!
#IBOutlet var projectNumTitle: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
projectNumLabel.text = projectNum
projectNumTitle.title = projectNum
println(projectNum)
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks!
You are defining prepareForSegueinside the button action function. It is a ViewController function to be overridden.
Your solution can be way more simpler:
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = segue.identifier
}
}
}
Note you do not need the button outlets, since you just configure them in the storyboard with the proper segue identifier. Unless you need some other custom action to be triggered by the buttons.
And:
class Project1ViewController: UIViewController {
var projectNum:String!
#IBOutlet var projectNumLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
projectNumLabel.text = projectNum
self.title = projectNum
println(projectNum)
}
}
Note I just set the title property of Project1ViewController in order to present the projectNum as the title in the navigation controller. I assume your controllers are embedded in a navigation controller and the ViewController's buttons has show segues to Project1ViewController.

Resources