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) {
}


}
Pavel_K
  • 8,216
  • 6
  • 44
  • 127
Karen C
  • 11
  • 1
  • https://stackoverflow.com/a/47257112/6080920 check this if it helps you – iOS Geek Nov 22 '17 at 07:16
  • Consider this: https://stackoverflow.com/questions/33234180/uitableview-example-for-swift. Also, searching the web for 'UITableView examples' is a good place to start. – Daniel Nov 22 '17 at 07:20
  • Can you show us your storyboard setup so we can help you out – OverD Nov 22 '17 at 07:40

1 Answers1

1

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.

Faysal Ahmed
  • 6,464
  • 5
  • 23
  • 43