Karen C
Karen C

Reputation: 11

How to make the tableview display an item in an array with each button press in Swift 4.0?

I'd like the tableview to insert a new row with a text that corresponds to a specific button i've pressed, but I'm not certain how to specify that in my code / UI.

Basically, i'd like the text "button #1 pressed" to appear when I press button #1, "button #2 pressed" to appear when I press button #2, etc. How can I configure that?

TableViewController.swift

import UIKit

class TableViewController: UITableViewController {

var myArray = ["button #1 pressed", "button #2 pressed", "button #3 pressed"]

override func viewDidLoad() {
    super.viewDidLoad(
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = self.FruitVegArray[indexPath.row]

    return cell
}

}

SubViewController.swift

import UIKit

class SubViewController: UIViewController {

@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let tableVC = segue.destination as! TableViewController

}

@IBAction func button1action(_ sender: Any) {
}

@IBAction func button2action(_ sender: Any) {
}


}

Upvotes: 0

Views: 74

Answers (1)

Faysal Ahmed
Faysal Ahmed

Reputation: 7669

Initialize myArray as blank

 var myArray = [String]()

and return number of rows count form myArray.

override func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int {
    return myArray.count
}

And now when button1 pressed then simply add "button #1 pressed" text in the array and refresh table view. You need to access myArray from your "SubViewController" class then add the text.

myArray.append("button #1 pressed")
 tableView.beginUpdates()
 tableView.insertRows(at: [IndexPath(row: myArray.count-1, section: 0)], with: .automatic)
 tableView.endUpdates()

Same for button 2 or others.

Upvotes: 1

Related Questions