Home > OS >  How do I display label text in table view cell when pressing a button?
How do I display label text in table view cell when pressing a button?

Time:09-17

I have this UIlabel that displays text and I want to be able to press the addButton and then display the text in the tableViewCell. How would I be able to do that?

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


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

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    
    cell.textLabel?.text = amountLabelArray[indexPath.row]
    
    
    return cell
}


@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!


var amountLabelArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    
    tableView.delegate = self
    tableView.dataSource = self
    
}

@IBAction func oneButton(_ sender: Any) {

let number = 1
amountLabel.text = amountLabel.text!   String(number)
}



//this will add the amount to the table view cell
@IBAction func addButton(_ sender: Any) {
    
        amountLabelArray.append(amountLabel.text!)
        print("This is the array \(amountLabelArray)")
        amountLabel.text = ""

   }
 }

CodePudding user response:

Have you tried to call reloadData() on your tableView on button tap?

@IBAction func addButton(_ sender: Any) {
    amountLabelArray.append(amountLabel.text!)
    print("This is the array \(amountLabelArray)")
    amountLabel.text = ""
    tableView.reloadData()
}
    
  • Related