Ios 在表中保存按钮
我有一个从站点获取并输出到表的数据数组,我想添加一个按钮,将表中的某一行存储在数据库中,我如何实现它Ios 在表中保存按钮,ios,swift,Ios,Swift,我有一个从站点获取并输出到表的数据数组,我想添加一个按钮,将表中的某一行存储在数据库中,我如何实现它 let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) cell.textLabel?.text = news[indexPath.row].tittle let tipDouble = NumberFormatter().number(from: news[i
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
使用标签。
将标记设置为按钮。将标记值指定为index path.row值。然后单击按钮,您可以访问索引处的相应数据(如果是数组)
例:
最简单的解决方法是将button tag属性设置为行号,并在button操作中获取button tag来完成您的工作,即 在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中的按钮操作中,使用按钮标记跟踪行,即
@IBAction func buttonTapped(sender: UIButton) {
let row = sender.tag
// Do your stuff
}
如果执行删除和插入,则完全可以。但有一个解决办法
var arrData: dataTag = [dataTag]()
class dataTag {
var name:String?
.......
var tag: Int? = Date().IntegerValue. Here "anyUniqueEntry value".
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.button.tag = IndexPath.row
..
}
func buttonAction(sender:UIButton){
let data = arrData[sender.tag]
...
}
每个单元格中的按钮要放在哪里?不相关,我会将
NumberFormatter
和DataFormatter
代码从cellForRowAt
移动到您的数据模型代码中。@koen我想在每行中放置一个按钮,当您单击按钮时,例如在第二行中,第二行被保存请附上示例代码,以便op能够理解解决方案。他解释了解决方案。编写代码是很容易的。标记对于表格单元格不是一个好主意,在用户添加或删除数据后,您将得到错误的按钮。这有一个问题。单元格的行号可以更改。例如,如果删除前面的行,或插入新道路。您应该在数据源中存储一些可以让您独立于更改来识别单元格的内容。是的,使用标记不是最好的方法-请参阅一些更复杂的方法,这不是最好的方法,但对于简单的情况,您可以使用这种方法,因为它非常简单。
var arrData: dataTag = [dataTag]()
class dataTag {
var name:String?
.......
var tag: Int? = Date().IntegerValue. Here "anyUniqueEntry value".
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.button.tag = IndexPath.row
..
}
func buttonAction(sender:UIButton){
let data = arrData[sender.tag]
...
}