首页 > 解决方案 > 在外部函数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 删除一行吗

标签: iosswiftxcodeuitableview

解决方案


手势应该添加到表格单元格内部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
}   

推荐阅读