Swift。在表格中保存按钮

问题描述 投票:0回答:2

我有一个从站点获取并输出到表的数据数组,我想添加一个按钮,该按钮将在数据库中存储表中的特定行,我该如何实现呢?

   let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
    cell.textLabel?.text = news[indexPath.row].tittle
    let tipDouble = NumberFormatter().number(from: news[indexPath.row].time!)!.doubleValue
    let date = Date(timeIntervalSince1970: tipDouble)
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2") //Set timezone that you want
    dateFormatter.locale = NSLocale.current
    dateFormatter.dateFormat = "MM-dd HH:mm" //Specify your format that you want
    let strDate = dateFormatter.string(from: date)
    cell.detailTextLabel?.text = strDate
   return cell
ios swift
2个回答
0
投票

使用标签。将标签设置为按钮。将Tag值作为索引path.row值。然后在Button上单击,您可以在索引处访问相应的数据(如果为数组)。

例如:var arrData = [“ 5”,“ 6”,“ 7”,“ 8”]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

cell.button.tag = IndexPath.row

...

}

func buttonAction(sender:UIButton){

让数据= arrData [sender.tag]

...

}


0
投票

最简单的解决方法是将按钮标签属性设置为行号,并在按钮操作中获取按钮标签来完成您的工作,即

在您的tableView(:cellForRowAt:indexPath)中,将按钮标记添加为行号:

let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! YourTableViewClass
cell.[buttonName].tag = indexPath.row (In case you are just using the single section)

然后在viewController中的按钮动作中,使用button的标签跟踪行,即

@IBAction func buttonTapped(sender: UIButton) {
    let row = sender.tag
    // Do your stuff
}
© www.soinside.com 2019 - 2024. All rights reserved.