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.
Related
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)
}
Entering data into textfield, when clicked on add button then that textfield text gets appended into an array and is displayed in table cell. Now max 5 data i can append and show it in a cell which is working but in a cell there is a delete button which deletes the data appended. Now i want that when deleting the entry from cell one by one, the last remaining data in a cell should not be deleted and a toast message should be displayed saying that mandatory data cannot be deleted. Right now i am removing the data at a given index but all data is being deleted right now beacuse i dont know which condition to put for last cell not being deleted. Please help me
My code :
var rowIndex = Int()
#objc func deletecontact(sender: uibutton)
{
rowIndex = sender.tag
Self.openDeleteDialogPopup()
}
IBAction weak var func yesBtnClicked(sender:uibutton)
{
MyArr.remove(at: rowIndex)
Mytableview.reloaddata()
}
In the function where you are deleting the item from the array you need to check on if it has a count greater than 1 or not, if it is not, then you show the toast. If it is then you delete the row
#IBAction weak var func yesBtnClicked(sender:UIButton) {
guard MyArr.count > 1 else { //If we have more than one item, then don't enter the else block
//showToastHere
return
}
MyArr.remove(at: rowIndex)
MyTableview.reloadData()
}
I have a method which generates several buttons, all with the same properties. The buttons are arranged vertically, like that:
What I need is that when each of them is clicked, it is capable of recognizing if it is the first one from the top, or the second one etc., printing "I'am the first/second/etc one".
How can I do it considering that the method they have is the same?
If all you need is an integer, use the tag property in UIView.
If you have an array of buttons…
var buttons: [UIButton]
you could sort them by their position in their superview to determine their order:
var sortedButtons: [UIButton] {
return buttons.sorted(by: { $0.frame.origin.y < $1.frame.origin.y })
}
and then get the index of a button (and vice-versa):
func index(of button: UIButton) -> Int {
return sortedButtons.index(of: button)
}
func button(at index: Int) -> UIButton? {
guard index < buttons.count else { return nil }
return sortedButtons[index]
}
Then…
#IBAction func buttonClicked(_ sender: UIButton) {
guard let index = index(of: sender) else { return }
sender.setTitle("I am \(index)", for: .normal)
}
This would also work if you added your buttons to an Outlet Collection in a storyboard:
#IBoutlet var buttons: [UIButton]!
Quick and dirty approach:
When dragging the outlet for the button, for the connection type select "Outlet Collection". This will create an outlet "to" a button array. Then you can drag and drop the rest of your buttons to this array. The order you make the drag n drop will be the order of your buttons in the array.
Then you can easily access them by index.
Caution: Easily breakable if re-drag n dropping the collection.
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
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)
}