ios - 在外部函数swift中使用表行中的indexPath
问题描述
新的 swift 和 uni 项目,但我有一个表格视图,其中包含朋友详细信息的记录
用户可以选择编辑朋友或删除朋友。为此,我创建了一个长按手势来删除朋友,但我不确定如何将 indexPath 传递给函数
这是我目前的布局:
import UIKit
class view_19342665: UIViewController,UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var friends: [Friends] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "friends", for: indexPath)
cell.textLabel?.adjustsFontSizeToFitWidth = true;
cell.textLabel?.font = UIFont.systemFont(ofSize: 13.0)
cell.textLabel?.text = friends[indexPath.row].displayInfo
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let id = friends[indexPath.row].studentID
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.removeRecord(id: Int(id))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
let appDelegate = UIApplication.shared.delegate as! AppDelegate
friends = appDelegate.getFriendInfo()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(sender:)))
tableView.addGestureRecognizer(longPress)
self.tableView.rowHeight = 33.0
}
override var canBecomeFirstResponder: Bool{
return true
}
@objc func handleLongPress(sender:UILongPressGestureRecognizer ){
if sender.state == .began{
// delete user
}
else{
//edit user
}
}
}
现在我可以删除表函数中的行。
这就是我想要实现的目标:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let id = friends[indexPath.row].studentID
handleLongPress(id)
}
func handleLongPress(id : Int){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if sender.state == .began{
appDelegate.removeRecord(id: Int(id))
}
else{
appDelegate.editRecord(id: Int(id))
}
有人可以帮我在长按手势上使用 ID 删除一行吗
解决方案
手势应该添加到表格单元格内部cellForRowAt
而不是表格本身
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
cell.contentView.addGestureRecognizer(longPress)
cell.contentView.tag = indexPath.row
然后
@objc func handleLongPress(_ tap:UILongPressGestureRecognizer) {
guard tap.state == .ended && let index = tap.view?.tag else { return }
// use index
}
推荐阅读
- android - 新建的cmake项目如何链接第三方静态库?
- javascript - jQuery分页插件不突出第一页
- java - 为什么paintComponent多次绘制圆圈?
- java - Flink:java.io.NotSerializableException:redis.clients.jedis.JedisCluster
- c# - 如何在 SQL Server 2016 中安装全文搜索?
- android-studio - 仿真器错误:x86 仿真当前需要硬件加速
- javascript - 当多个样式附加到html中的给定单词时,如何使用范围API单击一次单词
- angular - 如何修复primeNG日历中的“未捕获(承诺)”错误
- python - Python 覆盖没有找到我自己的模块
- c# - 将 liteDB 文档存储在云(天蓝色)blob 存储中