ios - 通过其中的按钮从 UITableViewCell 传递数据

标签 ios swift uitableview

我需要通过按钮将 PostList[indexPath.row].id 传递给另一个 View Controller ,而不选择所有单元格:

    class UserNewFeeds: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let Shamar_URL = NSURL(string: "http://127.0.0.1/jadeed/fetchtimeline.php")

    var PostList = Array<Feeds>()

    var refresh = UIRefreshControl()

    @IBOutlet weak var CollectionList: UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()

        LoadNewFeeds()

        CollectionList.reloadData()

    }

    var FeedUser : String?

    @IBAction func refresh(_ sender: Any) {
        CollectionList.reloadData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return PostList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let Cell:NewFeedsCell = tableView.dequeueReusableCell(withIdentifier: "Feed", for: indexPath) as! NewFeedsCell

        Cell.Userimg.image = #imageLiteral(resourceName: "User")
        Cell.Fullname.text = PostList[indexPath.row].name
        Cell.Username.text = PostList[indexPath.row].username
        Cell.DatePost.text = PostList[indexPath.row].date
        Cell.PostView.text = PostList[indexPath.row].body
        Cell.PostID.text = PostList[indexPath.row].id
        Cell.come.tag = indexPath.row
        Cell.come.addTarget(self, action: #selector(UserNewFeeds.Connect), for: .touchUpInside)
        print(Cell.come.tag)
        return Cell
    }

    func Connect(_ sender: Any, event: Any, segue: UIStoryboardSegue) {
        performSegue(withIdentifier: "ID_Post", sender: sender)
        let touches = (event as AnyObject).allTouches!
        let touch = touches?.first!
        let currentTouchPosition = touch?.location(in: CollectionList)
        var indexPath = CollectionList.indexPathForRow(at: currentTouchPosition!)!

        if segue.identifier == "ID_Post" {
            let testCon = segue.destination as! UserComments
            testCon.id_post = PostList[indexPath.row].id
            print(PostList[indexPath.row].id!)
        }
        print("position:\(indexPath.row)")
    }

    override func viewWillAppear(_ animated: Bool) {

        CollectionList.estimatedRowHeight = 220
        CollectionList.rowHeight = UITableViewAutomaticDimension
    }

    func LoadNewFeeds() {

        let request = NSMutableURLRequest(url: Shamar_URL! as URL)

        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in

            if error != nil{
                print("error is \(error!)")
                return;
            }

            DispatchQueue.main.async(execute: {

                do {

                    let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:Any]

                    let parseJSON = myJSON
                    let PostList = parseJSON?["Timeline"] as! [[String:Any]]

                    DispatchQueue.global().sync {

                        self.PostList.removeAll()

                        for post in PostList {

                            self.PostList.append(Feeds(name: post["name"]! as! String , username: post["post_by"]! as! String , body: post["body"]! as! String , date: post["post_date"]! as! String, id: post["id_post"]! as! String))
                        }
                        self.CollectionList.reloadData()

                    }
                } catch {
                    print(error)
                }
            })

        }

        task.resume()
    }
}

我正在尝试使用这个函数但是失败了:

func Connect(_ sender: Any, event: Any, segue: UIStoryboardSegue) {
    performSegue(withIdentifier: "ID_Post", sender: sender)
    let touches = (event as AnyObject).allTouches!
    let touch = touches?.first!
    let currentTouchPosition = touch?.location(in: CollectionList)
    var indexPath = CollectionList.indexPathForRow(at: currentTouchPosition!)!

    if segue.identifier == "ID_Post" {
        let testCon = segue.destination as! UserComments
        testCon.id_post = PostList[indexPath.row].id
        print(PostList[indexPath.row].id!)
    }
    print("position:\(indexPath.row)")
}

这是错误:

 2017-10-02 03:44:41.235 Al-Jadeed[31709:211436] -[UITouchesEvent identifier]: unrecognized selector sent to instance 0x6000000f0400
2017-10-02 03:44:41.326 Al-Jadeed[31709:211436] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITouchesEvent identifier]: unrecognized selector sent to instance 0x6000000f0400'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010b5edb0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010ac3d141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010b65d134 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x000000010b574840 ___forwarding___ + 1024
    4   CoreFoundation                      0x000000010b5743b8 _CF_forwarding_prep_0 + 120
    5   Al-Jadeed                           0x000000010a46ddba _TFC9Al_Jadeed12UserNewFeeds7ConnectfTP_5eventP_5segueCSo17UIStoryboardSegue_T_ + 1850
    6   Al-Jadeed                           0x000000010a46e689 _TToFC9Al_Jadeed12UserNewFeeds7ConnectfTP_5eventP_5segueCSo17UIStoryboardSegue_T_ + 121
    7   UIKit                               0x000000010c359d82 -[UIApplication sendAction:to:from:forEvent:] + 83
    8   UIKit                               0x000000010c4de5ac -[UIControl sendAction:to:forEvent:] + 67
    9   UIKit                               0x000000010c4de8c7 -[UIControl _sendActionsForEvents:withEvent:] + 450
    10  UIKit                               0x000000010c4dd802 -[UIControl touchesEnded:withEvent:] + 618
    11  UIKit                               0x000000010c8831f9 _UIGestureEnvironmentSortAndSendDelayedTouches + 5553
    12  UIKit                               0x000000010c87e210 _UIGestureEnvironmentUpdate + 1409
    13  UIKit                               0x000000010c87dc43 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 484
    14  UIKit                               0x000000010c87ce0a -[UIGestureEnvironment _updateGesturesForEvent:window:] + 274
    15  UIKit                               0x000000010c3c8eea -[UIWindow sendEvent:] + 4092
    16  UIKit                               0x000000010c375a84 -[UIApplication sendEvent:] + 352
    17  UIKit                               0x000000010cb595d4 __dispatchPreprocessedEventFromEventQueue + 2926
    18  UIKit                               0x000000010cb51532 __handleEventQueue + 1122
    19  CoreFoundation                      0x000000010b593c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    20  CoreFoundation                      0x000000010b5790cf __CFRunLoopDoSources0 + 527
    21  CoreFoundation                      0x000000010b5785ff __CFRunLoopRun + 911
    22  CoreFoundation                      0x000000010b578016 CFRunLoopRunSpecific + 406
    23  GraphicsServices                    0x00000001114f6a24 GSEventRunModal + 62
    24  UIKit                               0x000000010c358134 UIApplicationMain + 159
    25  Al-Jadeed                           0x000000010a4bed67 main + 55
    26  libdyld.dylib                       0x000000010f73a65d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

最佳答案

您的转换失败是因为您发送的是 ViewController 作为 segue 的发送者,而不是按钮。

将您的 Connect 方法更改为:

 func Connect(sender: UIButton) {
    performSegue(withIdentifier: "ID_Post", sender: sender)
 }

现在更改按钮的选择器,使其将自身作为参数发送(并正确设置标签):

Cell.come.tag = indexPath.row
Cell.come.addTarget(self, action: #selector(UserNewFeeds.Connect(_:)), for: .touchUpInside)

关于ios - 通过其中的按钮从 UITableViewCell 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46516388/

相关文章:

iOS 13 UIBarButtonItem 使用 UISearchController 时不可点击且重叠 UINavigationBars

ios - iOS swift中隐藏导航栏的方式黑白差异

ios - 如何在swift中从被调用方法中识别调用方法

ios - 如何创建一个 UIView,根据按下显示 View 的按钮来显示某些信息?

swift - swift,有没有办法通过名字选择一个 Sprite ?

iphone - 新 View Controller 中的电影播放器​​不播放来自动态 URL iPhone iOS 的电影

ios - 自定义 UITableView 单元格错误

swift - 在 Cocoa 应用程序中使用 SceneKit

iphone - UITableViewCell 文本很长

ios - 如何从用户函数中获取对单元格的引用