0

I want to take selected cell as a text, and save it in "var productName" as a String. I've tried to use didSelectRowAt funcion, but I don't know how to implement it.

That's my code:

import UIKit

class ChooseProductViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var productName: String? = ""
var workModel: ActualValues?
var closureBlock2: (() -> Void)?
@IBOutlet weak var checkButton: UIButton!


let productList : [String] = ["Almond 20g",
                              "Almond 40g",
                              "Baharat Spice Mix 2g",
                              "Baharat Spice Mix 4g",
]

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

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

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}



@IBAction func checkButton(_ sender: UIButton) {
    workModel?.product = productName
    closureBlock2?()
    self.dismiss(animated: true, completion: nil)
}



func configureProduct(model: ActualValues) {
    workModel = model
}


}

How can I fix it?

  • 1
    To be clear your question is "How to detect Cell selection in UITableView - Swift" here is the answer: [https://stackoverflow.com/questions/28430232/how-to-detect-cell-selection-in-uitableview-swift/28430422] – Nazir Mar 26 '20 at 11:06

1 Answers1

2

Something like this is probably what you want?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    productName = productList[indexPath.row]
}

And make sure you've set the data source and delegate, and that the table view allows seletion:

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