Add textfield outlet collection together - ios

I want to print the total of all of the textfields connected to cool textfield collection. There are only 2, in the log file.
import UIKit
class ViewController: UIViewController {
#IBOutlet var cool: [UITextField]!
#IBAction func press(_ sender: Any) {
for view in cool {
((cool.text! as NSString).integerValue += ((cool.text! as NSString).integerValue
}
}
}

If you want to add up all of the text fields, then simply do:
#IBAction func press(_ sender: Any) {
var total = 0
for view in cool {
if let text = view.text, let num = Int(text) {
total += num
}
}
print("The total is \(total)")
}
Don't force unwrap optionals. Don't use NSString in Swift.

Related

how can I add a addition feature into my Xcode project

I have a textfield in my firstViewContoller and thats where the user types in some numbers. Then in my secondViewController i have a label and in that label I want the number entered by the user to be shown. I have done till this but I dont know how I can take the value the user enters in the textfield every time and add it all up and show the result in the label. For example the user enters 5 so now the label is showing 5 then the user types in 20 and now i want the label to add that up and show 25 and keep on adding what the user enters.
// ViewController.swift
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var amountSpent: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
amountSpent.delegate = self
amountSpent.keyboardType = .numberPad }
private func amountSpent(_ amountSpent: UITextField,
shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
return string.rangeOfCharacter(from: invalidCharacters) == nil }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultViewController = segue.destination as! ResultViewController
resultViewController.recievedInt = amountSpent.text!
}
#IBAction func buttonPressed(_ sender: Any) {
self.performSegue(withIdentifier: "goToResult", sender: nil) } }
// ResultViewController.swift
import UIKit
class ResultViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var totalAmount: UILabel!
var recievedInt = ""
override func viewDidLoad() {
super.viewDidLoad()
totalAmount.text = recievedInt
}
}
Convert the new and the existing values from string to Int and add them together before setting the label to the new total
class ResultViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var totalAmount: UILabel!
var recievedInt = ""
override func viewDidLoad() {
super.viewDidLoad()
if let newValue = Int(recievedInt), let total = Int(totalAmount.text!) {
let newTotal = newValue + total
totalAmount.text = "\(newTotal)"
}
}
An alternative way to do it could be
override func viewDidLoad() {
super.viewDidLoad()
let newValue = Int(recievedInt) ?? 0
let total = Int(totalAmount.text!) ?? 0
let newTotal = newValue + total
totalAmount.text = "\(newTotal)"
}
Create a string variable to store the total value
var totalValue = "0"
Add the below method to your project. This will add all your entered values and will return the total value as a string.
private func getTotalCount(string: String) -> String {
let strTotal = "\(totalCount) + \(string)"
let arithmeticExpression = NSExpression(format: strTotal)
let additionResult = arithmeticExpression.expressionValue(with: nil, context: nil) as! Int
return String(additionResult)
}
You will click the done/return button after you entered the count in the text field, the delegate method will be triggered. Call the getTotalCount() method inside the delegate method as below:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
totalCount = self.getTotalCount(string: textField.text ?? "0")
textField.resignFirstResponder()
return true
}
Thus adding new counts will be automatically handled inside the UITextField delegate method. You just need to pass the totalValue to the next View Controller like this:
let resultViewController = segue.destination as! ResultViewController
resultViewController.recievedInt = totalCount

Hiding UIButton if variable has certain value?

I want to hide a UIButton as long as a certain variable has not reached a certain value.
I tried some setHidden and isHidden setups, but I guess I did it all wrong. I don't exactly know where to put these commands.
I have looked for a solution at almost every webpage but I got no idea what everybody is talking about.
import UIKit
class ViewController: UIViewController {
let startvalue = 1000000
#IBOutlet weak var Counter: UITextField!
#IBAction func Button(_ sender: UIButton) {
if number > 1{
number -= 1
Counter.text = String(number)
} else {
Counter.text = "Hurray"
}
}
#IBOutlet weak var Reset: UIButton!
#IBAction func Reset(_ sender: UIButton) {
if number == 1{
number = startvalue
Counter.text = String (number)
}
}
override func viewDidLoad() {
var number = startvalue {
didSet {
if number < 1 {
Reset.isHidden = false
}
}
}
super.viewDidLoad()
}
}
I don't now what I need to put where to hide Result as long as number is greater than 1.
Handle it in the didSet of the variable.
var number = startValue {
didSet {
if number < 1 {
yourButton.isHidden = false
}
}
}
Now, whenever your number is changed, the didSet block will check if the value is less than 1. If so, it'll unhide the button.
Note: Make sure the button is hidden before the view shows. Also, make sure to hide the button if needed on resetting.
Use lowerCamelCase for variable names like they say in the API design guidelines.

How to detect focused UITextField in Container view from Parent View Controller

I have a container view with multiple text boxes on it. I also have a button in Parent View controller(custom keypad). What I'm trying to do is select text box first & when I tap on the button I wanted some value to be populated to that last selected/focused textbox.
How can I do that? any alternative ways are welcome too. (I am having multiple container-views in the original code and try to use one keypad for all the views)
class MainViewController: UIViewController {
var weightVC : WeightViewController!
var focusedElement : UITextField
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "weight") {
weightVC = segue.destination as? WeightViewController
}
}
#IBAction func button1Clicked(_ sender: Any) {
if weightVC != nil {
weightVC.sampleTextBox1.text = "1"
//I want this sampleTextBox1 to be dynamic like weightVC.focusedInput = "1"
}
}
}
extension MainViewController:ChildToParentProtocol {
func setFocusedElement(with value: UITextField){
focusedElement = value
}
}
Container View Controller
protocol ChildToParentProtocol: class {
func setFocusedElement(with value:UITextField)
}
class WeightViewController: UIViewController {
weak var delegate: ChildToParentProtocol? = nil
#IBOutlet weak var sampleTextBox1: UITextField!
#IBOutlet weak var sampleTextBox2: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
// sampleTextBox1 Editing Did Begin event
#IBAction func editBeginSampleText1(_ sender: Any) {
print("edit begin")
delegate?.setFocusedElement(with: sampleTextBox1)
}
}
In other words, I simply want to keep a reference to last focused UITextFild when a button is tapped. Hope my requirement is clear enough. Please guide me if there is a way to achieve this.
Thanks
If I understood your question correctly you can keep track on which UITextField is tapped by using it's tag. And you can use UITextFieldDelegate to get the selected UITextField tag.
Consider the below code for WeightViewController
protocol ChildToParentProtocol: class {
//Changed value to Int for passing the tag.
func setFocusedElement(with value: Int)
}
import UIKit
class WeightViewController: UIViewController {
#IBOutlet weak var tf1: UITextField!
#IBOutlet weak var tf2: UITextField!
var selectedTFTag = 0
weak var delegate: ChildToParentProtocol? = nil
override func viewDidLoad() {
super.viewDidLoad()
//Assign delegate and tags to your TF
tf1.delegate = self
tf2.delegate = self
tf1.tag = 1
tf2.tag = 2
}
}
extension WeightViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
//Get the selected TF tag
selectedTFTag = textField.tag
//Pass tag to parent view
delegate?.setFocusedElement(with: selectedTFTag)
}
}
Now in your parent view ViewController you need to make some modification. I have added comments where I made changes to achieve your requirement.
import UIKit
//You need to confirm your ChildToParentProtocol with your UIViewController
class ViewController: UIViewController, ChildToParentProtocol {
var selectedTFTag = 0
var weightVC : WeightViewController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "weight" {
weightVC = segue.destination as? WeightViewController
//You need to pass delegate to containerview to make it working.
weightVC.delegate = self
}
}
#IBAction func btn1Tapped(_ sender: Any) {
//According to selected Tag perform your action
if selectedTFTag > 0 {
switch selectedTFTag {
case 1:
//set up first UITextField
weightVC.tf1.text = "First textfield was selected"
print("1")
case 2:
//set up second UITextField
weightVC.tf2.text = "Second textfield was selected"
default:
break
}
}
}
#IBAction func btn2Tapped(_ sender: Any) {
//According to selected Tag perform your action
if selectedTFTag > 0 {
switch selectedTFTag {
case 1:
//set up first UITextField
weightVC.tf1.text = "First textfield was selected"
print("1")
case 2:
//set up second UITextField
weightVC.tf2.text = "Second textfield was selected"
default:
break
}
}
}
func setFocusedElement(with value: Int) {
//Get selected TF tag with delegate
selectedTFTag = value
}
}
You can check THIS demo project for more info.

How can I change the title of a group of buttons with an array?

I have two IBAction groups with three buttons each.
Each button has a different tag - within each group: 1, 2 and 3.
I have three arrays, with three values each.
I want to press the first button of the first IBAction and change the title of the three buttons in the second IBAction, based on the group of arrays.
Here is the code:
import UIKit
class ViewController: UIViewController {
var firstArray = ["A1","A2","A3"]
var secondArray = ["B1","B2","B3"]
var thirdArray = ["C1","C2","C3"]
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func greenButtons(_ sender: UIButton) {
if sender.tag == 1 {
//change the title of the grayButtons with the firstArray
}
if sender.tag == 2 {
//change the title of the grayButtons with the secondArray
}
if sender.tag == 3 {
//change the title of the grayButtons with the thirdArray
}
}
#IBAction func grayButtons(_ sender: UIButton) {
}
}
You can try
// create outlet group for each
#IBOutlet weak var greenButtons:[UIButton]!
#IBOutlet weak var grayButtons:[UIButton]!
Inside action of greenButtons
grayButtons.forEach { $0.setTitle(firstArray[$0.tag - 1],for:.normal) }
Instead of if check you can construct the array as
let allArr = [ ["A1","A2","A3"], ["B1","B2","B3"],["C1","C2","C3"]]
Then
grayButtons.forEach { $0.setTitle(allArr[sender.tag - 1][$0.tag - 1],for:.normal) }

Code crashing in during runtime

I am learning swift3 programming but after executing my calculator app its crashing in between. Please check the below code.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var commmon_button: UIButton!
var a: Int?
var b: Int?
var sum: Int?
var val = ""
#IBOutlet weak var text_feild: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func clik_button(_ sender: UIButton) {
val=String(sender.tag)
text_feild.text = text_feild.text! + val
}
#IBAction func fn_addition(_ sender: UIButton) {
a = Int(text_feild.text!)
}
#IBAction func fn_answer(_ sender: UIButton) {
b = Int(text_feild.text!)
sum = a! + b!
a = 0
b = 0
text_feild.text = nil
text_feild.text = String(sum!)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
During run time i am getting crash at fn_addition by saying Thread 1 breakpoint 2.1
Initiliaze your variables as below
var a = 0
var b = 0
var sum = 0
Replace your methods with below methods.
#IBAction func clik_button(_ sender: UIButton) {
guard let value = String(sender.tag), let text = text_feild.text
else {
return
}
text_feild.text = text + value
}
#IBAction func fn_addition(_ sender: UIButton) {
guard let aValue = Int(text_feild.text)
else{
return
}
a = aValue
}
#IBAction func fn_answer(_ sender: UIButton) {
guard let bValue = Int(text_feild.text)
else{return}
b = bValue
sum = a + b
a = 0
b = 0
text_feild.text = ""
text_feild.text = String(sum)
}
Suggestion: You are using same text field for taking a , b values and for showing sum result. It is better to use two different text fields for taking a and b values separately. Take a label to show sum value.

Resources