Ios 在外部函数swift中使用来自表行的indexPath
对于swift和uni项目来说都是新手,但我有一个表视图,其中保存了朋友详细信息的记录 用户可以选择编辑朋友或删除朋友。 为此,我创建了一个删除好友的长点击手势,但我不确定如何将indexPath传递给函数 这是我当前的布局:Ios 在外部函数swift中使用来自表行的indexPath,ios,swift,xcode,uitableview,Ios,Swift,Xcode,Uitableview,对于swift和uni项目来说都是新手,但我有一个表视图,其中保存了朋友详细信息的记录 用户可以选择编辑朋友或删除朋友。 为此,我创建了一个删除好友的长点击手势,但我不确定如何将indexPath传递给函数 这是我当前的布局: import UIKit class view_19342665: UIViewController,UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITab
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
}
}
}
现在我可以删除table函数中的行
这就是我努力实现的目标:
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
然后
我不会用长时间的轻拍动作;表视图支持标准的向左滑动以删除我仍在学习swift的基础知识这是一项复杂的任务吗?@Paulw11在示例代码中对象对对象指什么。删除我收到错误“找不到对象”在您的情况下,它将是您的
朋友
数组。您还需要从任何持久性存储中删除数据,例如核心数据或正在使用的任何数据。另外,我不建议使用AppDelegate作为数据访问类。应该有一个模型类来处理这个问题。
@objc func handleLongPress(_ tap:UILongPressGestureRecognizer) {
guard tap.state == .ended && let index = tap.view?.tag else { return }
// use index
}