How to use textfield to enter numbers into a array (swift3) - ios

I have a textfield that I would like the user to be able to enter numbers for a array in. Ideally the button would save the number, then clear the textfield for another number to be enter. This would be a process that would just go in a loop. So its just save the number, clear the number, repeat infinitely.
import UIKit
class ViewController: UIViewController {
#IBOutlet var enterText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func submitText(_ sender: Any) {
}}

Lets define and array.
var arrayOfInt = [Int]()
Suppose you have button action method and textField Object (could be IB outlet) to which user enters number.
#IBAction func submitText(_ sender: Any) {
if let text = textField.text {
if let number = Int(text){
arrayOfInt.append(number)
}else {
print("Please enter number")
}
}
}

Related

How to transfer information from one IBAction to another

The code should work as follows: On one View I click tag button and tagButtonPressed IBAction should set tag variable to sender.tag of the tag button. It works well. Then user should click 'send' button and sharePressed IBAction should use the tag variable which equals to sender.tag of the 'tag' button, and print the updated value of tag variable. Unfortunately it doesn't work.
import UIKit
class ShareViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
var tag : Int = 1
#IBOutlet weak var shareTextField: UITextView!
#IBAction func tagButtonPressed(_ sender: UIButton) {
tag = sender.tag // lets say sender.tag = 4
print(tag) // It prints 4
}
#IBAction func sharePressed(_ sender: Any) {
print(tag) // it prints 1 and i want it to print also 4
}
}
Your code is correct. Somewhere else (not shown) you're re-setting the tag value to 1.

How to change label text according to TextField content while edited

I've just approached Swift and I'm trying to learn some very basic stuff.
I'm trying to achieve this:
I have a TextField and an Label, and I want the Label to be set to a specific emoji, according to the TextField text (which should a country name).
Example:
If the TextField contains the word "Italy", I want the Label to be set to "🍕".
If the TextField contains the word "Mexico", the Label should be set to "🌮".
This should happen while the TextField is being edited, not using any button to confirm the text in it.
This is my (not working, obviously) code.
#IBOutlet weak var emojiLabel: UILabel!
#IBOutlet weak var myTestField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
changeLabel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func changeLabel() {
emojiLabel.text = "🌎"
var countryName = myTestField.text
if (countryName == "Italia") {
emojiLabel.text = "🍕"
print (emojiLabel)
}
}
The first thing you want to do is set up a dictionary with all of the pairs you want, for example:
//Put this line outside of viewDidLoad
var dictionary: [String: String] = [:]
//Put these lines inside of viewDidLoad
dictionary["Italy"] = "🇮🇹"
dictionary["Mexico"] = "🌮"
//...Add more pairs to the dictionary
Now that you have defined all of your pairs, the next thing you want to do is setup the delegate of your text field. Doing this allows you to run some block of code whenever text is entered into your textfield. First, in your view controllers class definition, you want to conform to the UITextFieldDelegate:
class ViewController: UIViewController, UITextFieldDelegate {
//...rest of the code in the view controller
}
Then, in your viewDidLoad, you want to set the delegate of your text field to self (a.k.a. to this view controller, which we have just conformed to the UITextFieldDelegate):
override func viewDidLoad() {
super.viewDidLoad()
//...rest of code in viewDidLoad
myTestField.delegate = self
}
Now, with all of that out of the way, we want to call this function, just start typing textfield and it will autocomplete because we have already conformed to the UITextFieldDelegate:
func textFieldDidEndEditing(_ textField: UITextField) {
//...This function is called EVERY time editing is finished in myTestField
}
Ok, so inside of the textFieldDidEndEditing function, all we need to do is check what was entered in myTestField and see if it matches any of the keys in the dictionary we created in the first step...if it does, then we are finally going to update our label:
func updateLabel(textField: UITextField) {
//we are using guard here because we are dealing with optional values,
//meaning that textField.text doesn't necessarily have a value, and
//dictionary[text] may not actually have a value either.
guard let text = textField.text,
let labelText = dictionary[text] else {return}
//Now we are going to actually update our label
emojiLabel.text = labelText
}
Ok, looking good, last thing to do is just call our updateLabel function inside of the textFieldDidEndEditing function:
func textFieldDidEndEditing(_ textField: UITextField) {
//...This function is called EVERY time editing is finished in myTestField
updateLabel(textField: textField)
}
That's it!
I made it thanks to Teetz comment.
This is my working code if someone else needs it:
EDIT 1: I strongly recommend to use the Greg solution, marked as answer.
#IBOutlet weak var emojiLabel: UILabel!
#IBOutlet weak var myTestField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myTestField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
textFieldDidChange(myTestField)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#objc func textFieldDidChange(_ textField: UITextField) {
emojiLabel.text = "🌎"
var countryName = myTestField.text
if (countryName == "Italia") {
emojiLabel.text = "🍕"
}
}

Delegate Pattern In Swift w/o Segue

I cannot find an example of the Swift Delegate pattern without the segue included. I want the boss class(boss view) to send orders to the worker class(worker view) and print what the boss says to print. The Delegate is coming up 'nil' when I press either of the buttons (doThisButton/doThatButton) on the boss page.
Edit: My Views are set up as follows: the 'TheBoss' VC has three buttons, 'doThisButton', 'doThatButton', and 'goToTheWorker' button. the 'TheWorker' VC has a text box. The 'doThisButton'/'doThatButton' send information to the text box in 'TheWorker' VC, but do not make 'TheWorker' VC appear. the 'goToTheWorker' button is a show segue that was set up in storyboard to open the 'TheWorker' VC.
This is the 'Boss' class
import UIKit
protocol TheBossesOrdersDelegate {
func doThis(numberOne: Int, stringOne: String)
func doThat(numberTwo: Int, stringTwo: String)
}
class TheBoss: UIViewController {
// Declair Delegate
var delegate: TheBossesOrdersDelegate!
#IBAction func doThisButton(_ sender: UIButton) {
delegate.doThis(numberOne: 75, stringOne: "Do This")
}
#IBAction func doThatButton(_ sender: UIButton) {
delegate.doThat(numberTwo: 125, stringTwo: "Do That")
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
This is the 'Worker' class
import UIKit
class TheWorker: UIViewController, TheBossesOrdersDelegate {
let theBoss = TheBoss()
func doThis(numberOne: Int, stringOne: String) {
print("the boss send this number to print: \(numberOne) and this string: \(stringOne)")
theWorkersTextBox.text = "Number: \(numberOne) String:\(stringOne)"
}
func doThat(numberTwo: Int, stringTwo: String) {
print("the boss send this number to print: \(numberTwo) and this string: \(stringTwo)")
theWorkersTextBox.text = "Number: \(numberTwo) String:\(stringTwo)"
}
#IBOutlet weak var theWorkersTextBox: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
theBoss.delegate = self
}
}
It looks like your code has the worker create the boss. Since you do that, you need to tell the boss who it's delegate is:
import UIKit
class TheWorker: UIViewController, TheBossesOrdersDelegate {
let theBoss = {
let result = TheBoss()
result.delegate = self //This is the line you are missing
return result
}()
//The rest of your TheWorker class's code...
}
EDIT:
Based on your comment, you have a confused mess. Post the Boss class code for the button that displays a worker view controller. And your title says "w/o segue", but then in your comment you say "the boss is presented first and contains a button that connects to the worker via a show segue." What? you said without a segue.

Change the text of a label with a button in iOS

Firstly, let me say I'm new to Swift and Xcode. I have a label that displays some text and I want that text to change when a button is pressed.
Here is the code in the UIViewController:
var txt = "Hey"
#IBOutlet weak var Text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
showText()
}
func showText(){
Text.text = txt
}
#IBAction func Button(_ sender: Any) {
txt = "Hello"
}
The buttons and labels are correctly linked to their main.storyboard counterparts. When I run this and press the button the text doesn't change.
viewDidLoad() is only called one time when the ViewController is created. showText() needs to be called after txt is set if you want to display it. One way to automate this is to add a property observer to txt to call showText() when txt is updated:
var txt = "Hey" {
didSet {
showText()
}
}
I will add that it is more flexible and perhaps elegant to have your showText() method take the actual text to show as an argument, instead of depending on some internal state (the value of the property txt: String, that isn't immediately evident at the call site) to accomplish its task:
#IBOutlet weak var textLabel: UILabel!
func showText(_ text: String){
self.textLabelabel?.text = text
// (optional chaining to avoid crash if accidentally
// called before viewDidLoad())
}
#IBAction func buttonAction(_ sender: Any) {
self.showText("Hello") // From here it is clear what text will be shown
}
change your code as per below
var txt = "Hey"
#IBOutlet weak var Text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
showText()
}
func showText(){
Text.text = txt
}
#IBAction func Button(_ sender: UIButton) {
txt = "Hello"
showText()
}
Change Text of label with button just need to pass the text in label;
//Outlets
#IBOutlet weak var firstLabel: UILabel!
#IBOutlet weak var secondLabel: UILabel!
//Button Action
#IBAction func textChabge(_ sender: Any) {
firstLabel.text = "newText"
secondLabel.text = "newText"
}
just change your IBAction like this.
#IBAction func Button(_ sender: Any) {
txt = "Hello"
showText()
}

swift images array code back button error

I want to slide from the pictures. My code is:
#IBOutlet weak var image: UIImageView!
var resimler=["01.jpg","02.jpg","03.jpg","04.jpg","05.jpg"]
var index=0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func gerileBttn(sender: UIButton) {
index--
if index==resimler.count {index=0}
image.image=UIImage(named: resimler[index])
}
#IBAction func ilerle(sender: UIButton) {
index++
if index==resimler.count {index=0}
image.image=UIImage(named: resimler[index])
}
When I press forward moving pictures. However, when it comes to the first picture when I press the back key "array" error whether the program crashes..
How can I solve this problem.
Thanks for the help..
Looks like your index may be going negative. Perhaps this (assuming you want it to wrap)?
#IBAction func gerileBttn(sender: UIButton) {
index--
if index<0 {index=resimler.count-1}
image.image=UIImage(named: resimler[index])
}

Resources