【问题标题】:How to select specific Cell in UITableView and save it in String var - Swift如何在 UITableView 中选择特定的 Cell 并将其保存在 String var - Swift
【发布时间】:2020-03-26 10:57:36
【问题描述】:

我想将选定的单元格作为文本,并将其作为字符串保存在“var productName”中。我尝试过使用 didSelectRowAt 函数,但不知道如何实现。

这是我的代码:

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
}


}

我该如何解决?

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

这样的东西大概就是你想要的吧?

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

并确保您已设置数据源和委托,并且表格视图允许选择:

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

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2018-08-02
    • 2015-05-31
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多