creating an array the splits user input into 6 different textfields (swift) - ios

I am new to Swift but I have managed to setup some code for an OTP authentication page but I need help recreating the code.
I want to have the textfields setup into an array and when I get a value (ex "123456") I want to split the numbers 6 ways and add 1 digit per textfield (1,2,3,4,5,6) and vice versa. How do I go about doing this?
Right now my code for my current setup is:
import UIKit
import FirebaseAuth
class PhoneAuthenticationViewController: UIViewController {
#IBOutlet weak var Auth1: UITextField!
#IBOutlet weak var Auth2: UITextField!
#IBOutlet weak var Auth3: UITextField!
#IBOutlet weak var Auth4: UITextField!
#IBOutlet weak var Auth5: UITextField!
#IBOutlet weak var Auth6: UITextField!
#IBAction func textEditDidBegin(_ sender: UITextField) {
print("textEditDidBegin has been pressed")
if !(sender.text?.isEmpty)!{
sender.selectAll(self)
//buttonUnSelected()
}else{
print("Empty")
sender.text = " "
}
}
#IBAction func textEditChanged(_ sender: UITextField) {
print("textEditChanged has been pressed")
let count = sender.text?.count
//
if count == 1{
switch sender {
case Auth1:
Auth2.becomeFirstResponder()
case Auth2:
Auth3.becomeFirstResponder()
case Auth3:
Auth4.becomeFirstResponder()
case Auth4:
Auth5.becomeFirstResponder()
case Auth5:
Auth6.becomeFirstResponder()
case Auth6:
Auth6.resignFirstResponder()
default:
print("default")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
Auth1.delegate = self
Auth2.delegate = self
Auth3.delegate = self
Auth4.delegate = self
Auth5.delegate = self
Auth6.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Auth1.becomeFirstResponder()
}
}

Try this code if this helps you
import UIKit
/// Extension for String
extension String {
/// Function which will split string in parts
func splitInParts() -> [String]{
/// Array
var splittedArray = [String]()
/// Split STring according to characters
for char in self {
/// Append character as string
splittedArray.append(String(char))
}
/// Return
return splittedArray
}
}
class TwoScrollViewStack: UIViewController {
/// OTP String
var myString : String = "123456"
/// Labels
private var otp1 = UILabel()
private var otp2 = UILabel()
private var otp3 = UILabel()
private var otp4 = UILabel()
private var otp5 = UILabel()
private var otp6 = UILabel()
/// Label Array
private var labelArray = [UILabel]()
override func viewDidLoad() {
super.viewDidLoad()
/// Assign Label in Array
labelArray = [otp1,otp2,otp3,otp4,otp5,otp6]
/// Get Splitted String
let splittedStringArray = self.myString.splitInParts()
/// Sssign Values to Labels
for i in 0..<splittedStringArray.count {
labelArray[i].text = splittedStringArray[i]
}
/// Check Output if necessary
print(splittedStringArray)
/// Output - ["1", "2", "3", "4", "5", "6"]
}
}

in below code,
switch sender {
case Auth1:
// add your logic to append entered character into auth1 textfield.
Auth1.text = sender.text ?? ""
Auth2.becomeFirstResponder()
...
// same in all case
...
}

Related

Check if input countains numbers in 2 fields in xcode

So i recently tried to create a very simple calcylator in xcode, the problem i have is when i press the calculate button when there is no numbers there the app crashes, and when i put anything that isnt a number there and press the calculate button it also crash, and i know it crash cause it cant convert nothing/non numbers into a double, but how do i check if it is numbers in the textfields and if it is it will show the result off the
equation and if there is no number it will just set the textfeilds to nothing
(faktor1.text = "") (faktor2.text = "") ...
well it looks like this right now (ränka ut means calculate)
here is the code i used,
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faktor1: UITextField!
#IBOutlet weak var faktor2: UITextField!
#IBOutlet weak var result: UILabel!
#IBOutlet weak var calculatebutton: UIButton!
#IBOutlet weak var clearui: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
result.text = ""
calculatebutton.layer.cornerRadius = 25.0
result.layer.cornerRadius = 25.0
clearui.layer.cornerRadius = 25.0
}
#IBAction func calculate( sender: Any) {
let input1 = Double(faktor1.text!)!
let input2 = Double(faktor2.text!)!
let calculation = input1 * input2
result.text = "(calculation)"
}
#IBAction func clearfnc( sender: Any) {
result.text = ""
faktor1.text = ""
faktor2.text = ""
}
}
You can simply unwrap your optionals the Swift way, instead of using ! (force unwrap)
This is an example using guard:
#IBAction func calculate(sender: Any) {
guard
let input1String = faktor1.text,
let input2String = faktor1.text,
let input1 = Double(input1String),
let input2 = Double(input2String)
else {
faktor1.text = ""
faktor1.text = ""
return
}
let calculation = input1 * input2
result.text = "\(calculation)"
}

can't append text to string array due to Initializer for conditional binding error

My code below works perfectly if i switch the strings for the ints. However with the String where it is it is not working.
import UIKit
class ViewController: UIViewController {
#IBOutlet var txt: UITextField!
var arrayOfInt = [String]()
#IBAction func submit(_ sender: Any) {
if let text = txt.text {
if let name = String(text){
arrayOfInt.append(name)
}}}
}
You are (unnecessarily) initialising a String from a String using String(text); Unlike Int(_ string:String) this is not a failable initializer.
It is possible that a String cannot be parsed to an Int, so you need to check that Int(text) didn't return nil, but a String can always be initialised from a String.
When you say
if let name = String(text) {
The compiler give you an error because the if let... conditional binding construct requires an optional, but String(text) does not return an optional.
Your code can be simplified to:
class ViewController: UIViewController {
#IBOutlet var txt: UITextField!
var arrayOfString = [String]()
#IBAction func submit(_ sender: Any) {
if let text = sender.text {
arrayOfString.append(text)
}
}
}

Converting string value from text field to integer

I'm really new to Swift and I am having problems with the conversion of a string (entered in a text field) to an integer.
I'm trying to create a small calculation app (I was following a tutorial on YouTube but it's old).
My app has 3 text fields, a label (that is meant to display the result), and a button to start the calculation.
Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var valueA: UITextField!
#IBOutlet weak var valueB: UITextField!
#IBOutlet weak var valueC: UITextField!
#IBOutlet weak var result: UILabel!
#IBAction func calculateTotal(_ sender: Any) {
var a:Int? = Int(valueA.text)
var b:Int? = Int(valueB.text)
var c:Int? = Int(valueC.text)
var answer = a! * b! * c!
}
}
Try this (crash free code and you can add n number of textfield/string values as a number string):
var arrayOfTextFieldValues = [valueA.text, valueB.text, valueC.text]
#IBAction func calculateTotal(_ sender: Any) {
if let multiplication = multiplication(arrayString: arrayOfTextFieldValues) {
print("Answer = \(multiplication)")
result.text = "\(multiplication)"
}
}
// handle operations
func multiplication(arrayString: [String?]) -> Int? {
var answer:Int?
for arrayElement in arrayString {
if let stringValue = arrayElement, let intValue = Int(stringValue) {
answer = (answer ?? 1) * intValue
}
}
return answer
}

Fatal error when unwrapping a segued string (swift3)

This is my code I don't know what I did wrong. All of the problems are in function steve. LebelText is a timer timer label that is segued from another view controller. So i want to take lebetText convert it to a int to subtract 1 from it then reconvert it back to a string to display the number.
This is view Controller a. The texted being segued is lebelText.
import UIKit
class testViewController: UIViewController {
#IBOutlet var lazel: UILabel!
#IBOutlet var plax: UIButton!
#IBOutlet var stopx: UIButton!
var timer = Timer()
var counter = 0.0
var isRunning = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let DestViewController : restultViewController = segue.destination as! restultViewController
DestViewController.LebelText = lazel.text!
}
#IBAction func play(_ sender: Any) {
if !isRunning{
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(testViewController.update), userInfo: nil, repeats: true)
}
plax.isEnabled = false
stopx.isEnabled = true
}
#IBAction func stop(_ sender: Any) {
plax.isEnabled = true
stopx.isEnabled = false
timer.invalidate()
isRunning = false
}
func update(){
counter += 0.1
lazel.text = String(format: "1%f", counter)
lazel.text = "\(counter)"
}}
this is view controller b. The goal is to go to take lebelText convert it to a int to subtracted 1 from it. Then convert it back to a string so it can be displayed.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var dxe: UILabel!
var LebelText = String()
let myInt = Int()
override func viewDidLoad() {
super.viewDidLoad()
steve()
}
func steve(){
var eq = LebelText
var intValue = Int(eq)
let vx = intValue! - 1
let ramit = String(vx)
dxe.text = ramit
}
ok so to get rid of the optional and to be sure it all works you should do like
if let intValue = Int(eq) {
vx = intValue - 1
dxe.text = String(vx)
} else {
//do some stuff if you cannot convert eq to Int
}
but I would recommend you to start with some easier tasks, it looks like you did not completely learn basics.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var someLabel: UILabel!
public var myText: String?
override func viewDidLoad() {
super.viewDidLoad()
self.parseData()
}
private func parseData(){
guard let unwrapedText = self.myText else {
//you didn't pass string
return
}
if let myInt = Int(unwrapedText) {
myInt = myInt - 1
self.someLabel.text = String(myInt)
} else {
//you string is not convertable to int
}
}
}
You Can just do this.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var dxe: UILabel!
var LebelText = String()
let myInt = Int()
override func viewDidLoad() {
super.viewDidLoad()
steve()
}
func steve(){
var eq = Int(LebelText.text)
eq = eq - 1
dxe.text = String(eq)
}

Is there a way to see if the value of a textfield is equal to a value in a dictionary in Swift?

I'm making a simple search engine in xcode. It is supposed to work by seeing if the text in a textfield is equal to a value in a dictionary, and if so, do an action, like this:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var SearchField: UITextField!
#IBOutlet weak var SearchButton: UIButton!
#IBOutlet weak var Result1: UILabel!
#IBOutlet weak var Result2: UILabel!
var possibleResults = ["Daniel":"www.example.com", "Bob":"www.asdf.com"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//if Go button is pressed
#IBAction func SearchButton(sender: AnyObject) {
//if Search field is equal to a value in possibleResults
if SearchField is equal to a value in possibleResults {
//makes result1 say hi
self.Result1.text = "Hi"
} else {
self.Result1.text = "No Results"
}
}
}
Also, keep in mind I am pretty new to Swift, so simple and direct answers would be helpful.
You can unwrap the text and check the result in one line, like following:
if let text = SearchField.text, result = possibleResults[text] {
print(result)
}
You can use:
if possibleResults[SearchField.text ?? ""] != nil {
// ...
}
or
if let _ = possibleResults[SearchField.text ?? ""] {
// ...
}
if you do not need value that you get from dictionary.
If you will use value from dictionary then replace underscore with variable name:
if let value = possibleResults[SearchField.text ?? ""] {
// ...
}

Resources