Repeatedly append to Array on Button Click Swift - ios

I have a button that is supposed to append the value of the cell's label to an array.
#IBAction func test(sender: AnyObject) {
var cellLabelArray = [""]
cellLabelArray.append(cell.cellLabel.text)
}
I assumed that as the more I selected the button, the longer the array would become.
Like : cellLabelArray = ["label", "label", "label", "label"] if I pressed it four times.
What I'm getting is that it just appends the text label once, what I want is to append multiple times, because the label changes.
it returns something like this: ["label"] no matter how many times I press the button
How would I do this using Swift?

The problem is that with this line:
var cellLabelArray = [""]
you're emptying cellLabelArray at the start of the method.
So declare and initialize cellLabelArray elsewhere in your code, ex:
var cellLabelArray:[String] = []
#IBAction func test(sender: AnyObject) {
cellLabelArray.append(cell.cellLabel.text)
}

Related

Swift UIbutton is clicked add a string and when clicked again it removes it

I'm a beginner in swift, I'm making an app in storyboard UIKit, and I need some help basically I need to set up a view controller that has buttons on it that when clicked add a string on the bottom of the VC, and if clicked again it will remove that same string. On the VC there going to be multiple buttons like this for options also on the bottom of the VC I need the label to update during the app also it should display like this for example. "Football","Basketball","Golf". It needs to be displayed just like that on the bottom with quotes and commas. I've to turn to make action buttons with a global array and put that inside each button but I can't figure out how to remove it when the button clicked again, also if you click the button again it'll add the same thing again so in the array you'll have two of the same strings. Anything would help.
P.S I need to do this in UIkit and Storyboard
You can make list of outlets to an array UIButton, handle list of actions when click into UIButton with a function. Using 'isSelected' property of UIButton to distinguish 'delete' or not.
class ViewController: UIViewController {
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet var allButtons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func didTapButton(_ sender: UIButton) {
sender.isSelected.toggle()
_updateDescription()
}
private
func _updateDescription() {
descriptionLabel.text = allButtons
.filter { $0.isSelected }
.compactMap { $0.titleLabel?.text }
.map { "\"\($0)\"" }
.joined(separator: ", ")
}
}

Swift adding items to array from text field input

I am trying to display a list of items on a shopping list. These items are added from two text fields (description and quantity). For some reason, I am not able to get the array to keep the previous items, instead, the previous items in the array disappear and the only item that shows was the most recent item entered. Can someone help me understand where I have gone wrong? Here is the code I have:
#IBAction func add(_ sender: UIButton) {
var shoppingList = [String]()
if let x = descriptionField.text{
if let y = quantityField.text{
if x != "" && y != "" {
if isStringAnInt(string: y){
shoppingList.append("\(y) x \(x)")
}else{
[...]
Your shopping list array is set as empty every time in button action. you need the declare the array outside the button action.
var shoppingList = [String]()
#IBAction func add(_ sender: UIButton)
You are declaring the array inside the function so as soon as you press the items add button it resets the previous array and that is the reason your item disappears. Declare your array outside the function and then use it inside the function. This will solve your issue.

append button title to array?

I have an empty array, and I have #IBAction func test(_ sender: UIButton) with 25 different buttons attached to this func. how can I write the code for appending a button title to the array, when pressed?
someArray.append = (this part that I can't figure out?)
Since I don't know which button/buttons will be pressed I can't just write someArray.append = ("buttonTitle")
(ive googled and searched in here for hours, but I can't find the solution)
if let title = sender.title(for: sender.state) {
someArray.append(title)
}
For multiple UIButtons with single IBOutlet Action you can add tags for each UIButton.
So if you've used StoryBoard for UIButtons, so when you click on single UIButton - navigate to Attribute Inspector & add tag to each button. As shown in below fig.1.0
I've set all UIButtons with different title & tags.
Once you set tags, for all buttons, then programmatically you can identify which button is clicked via single - onClick function.
#IBAction func Click(_ sender: UIButton) {
if let title = sender.title(for: sender.state){
print(title)
//Here we are identifying which button is pressed. If I pressed UIButton.tag = 1 then I'm just printing it's title, else appending UIButton value in array.
if sender.tag == 1 {
print(sender.title(for: sender.state))
}
else{
self.someArray.append(title)
}
}
}
So, in this way you can identify all your UIButton actions within a single event action.
#IBOutlet weak var btnoutlet: UIButton!
if let title = btnoutlet.currentTitle {
someArray.append(title)
}

Save label.text in swift4

Im currently developing a iOS app in which im going to keep track of our warehouse stock. It's a pretty simple app an just contains a lable and an stepper. The app is pretty much finished, but i don't get how to save the changed value of the label. I want to save it automatically so that when someone presses the "+" on the stepper, the value should save without pressing a extra save button
Current code:
//montageplatte
#IBOutlet weak var lbl_montageplatte: UILabel!
#IBAction func stepper_montageplatte(_ sender: UIStepper)
{
lbl_montageplatte.text = Int(sender.value).description
}
you can save it in UserDefaults.
#IBAction func stepper_montageplatte(_ sender: UIStepper) {
lbl_montageplatte.text = Int(sender.value).description
UserDefaults.standard.set(String(sender.value), forKey: "lblMontageplatte")
}
To get back value you can do as follow...
if let lblValue = UserDefaults.standard.object(forKey: "lblMontageplatte") as? String {
print(lblValue)
lbl_montageplatte.text = lblValue
}
Simple solution:
In the custom cell create an outlet for the stepper and a NSKeyValueObservation property
#IBOutlet weak var stepper : UIStepper!
var stepperObservation : NSKeyValueObservation?
In cellForRow in the controller add the key value observer
cell.stepperObservation = cell.stepper.observe(\.value, options: [.new]) { (stepper, change) in
print(change.newValue!)
}
Rather than printing the new value update the model (the item for the particular index path) and save the datasource array if necessary.

Variable going back to 0 when label saved

I made an app where I save a label that I can make it go up or down one number in my app. But if I lose out of my app and open it back up, if i make the label go up again than it resets back to zero and goes to one. This is because I have to set the variable value to zero. Here is my code:
#IBOutlet var goal: UILabel!
#IBAction func player1button(sender: AnyObject)
{
NSUserDefaults.standardUserDefaults().setValue(goal.text!, forKey:"firstGoal")
}
var goal1 = 0
#IBAction func goalUp(sender: AnyObject)
{
goal1++
goal.text = "\(goal1)"
}
override func viewDidLoad()
{
super.viewDidLoad()
goal.text = (NSUserDefaults.standardUserDefaults().objectForKey("firstGoal") as? String)
}
Im saving the goal number then calling it back later in the text. Please show me a way to fix it so it just adds on to the previous number.
in viewDidLoad() add
goal1 = Int((NSUserDefaults.standardUserDefaults().objectForKey("firstGoal") as? String)!)
this will set the int variable you are using to keep track of the goals to the correct value when the app loads. currently you are only setting the text label to the correct value.
or you can simply make var goal1 a global variable , just after the imports and before the class keyword , in case you don't need to keep the data till the next time you open the app itself

Resources