IOS Swift 如何获取 TableView 中点击时元素的值

IOS Swift how can I get the value of an element on Click in TableView

我有一个通过 Json 获取数据的自定义 TableView,我在该 tableView 中有一个名为 "FullName" 的按钮。该 FullName 显然具有用户名,但 OnClick 我想获得与该特定 TableViewCell 相对应的 "Profile_ID" 以便我可以保存它。我的代码将有助于解决问题

 class HomePageViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{


    @IBOutlet var StreamsTableView: UITableView!


    var names = [String]()
    var profile_ids = [String]()



    override func viewDidLoad() {
        super.viewDidLoad()
        StreamsTableView.dataSource = self

        let urlString = "http://"+Connection_String+":8000/streams"

        let url = URL(string: urlString)
        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            if error != nil {
               /// print(error)
            } else {
                do {

                    let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
                    if let Streams = parsedData["Streams"] as! [AnyObject]? {
                 // Getting Json Values       
                        for Stream in Streams {
                            if let fullname = Stream["fullname"] as? String {
                                self.names.append(fullname)
                            }


                            if let profile_id = Stream["profile_id"] as? String {
                                self.profile_ids.append(profile_id)
                            }


                            DispatchQueue.main.async {
                                self.StreamsTableView.reloadData()
                            }

                        }


                    }



                } catch let error as NSError {
                    print(error)
                }
                print(self.names)
            }

        }).resume()






    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func Fullname_Click(){
  // Where the # 32 is I would like to replace that with Profile_ID
        UserDefaults.standard.set("32", forKey: "HomePage_Fullname_ID")
        let navigate = self.storyboard?.instantiateViewController(withIdentifier: "Profiles") as? MyProfileViewController
        self.navigationController?.pushViewController(navigate!, animated: true)
    }



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {

            tableView.backgroundColor = UIColor.clear
            return names.count

    }

    private func tableView(tableView: UITableView,height section: Int)->CGFloat {
        return cellspacing
    }




    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {

        let mycell = self.StreamsTableView.dequeueReusableCell(withIdentifier: "prototype1", for: indexPath) as! HomePage_TableViewCell
        mycell.Fullname.setTitle(names[indexPath.row], for: UIControlState.normal)
       // Click Event below
         mycell.Fullname.addTarget(self, action: "Fullname_Click", for: UIControlEvents.touchUpInside)
            mycell.Fullname.tag = indexPath.row


        tableView.separatorColor = UIColor.clear


        return mycell


    }


}

主要问题出在这段代码上

  func Fullname_Click(){
      // Where the # 32 is I would like to replace that with Profile_ID
            UserDefaults.standard.set("32", forKey: "HomePage_Fullname_ID")
            let navigate = self.storyboard?.instantiateViewController(withIdentifier: "Profiles") as? MyProfileViewController
            self.navigationController?.pushViewController(navigate!, animated: true)
        }

注意我硬编码了数字 32 我想要的是用 profile_id[=26= 的值替换数字 32 ] 属于那个特定的 TableView Cell 。 profile_id 可通过此代码访问

                   if let profile_id = Stream["profile_id"] as? String {
                            self.profile_ids.append(profile_id)
                        }

我可以找到一种方法将它传递给 FullName_Click 函数...

解决方案一: 假设,每个名字都存在一个profile_id,

您可以使用索引路径访问。

@IBAction func resetClicked(sender: AnyObject) {
 let row = sender.tag
 let pid = self.profile_ids[row]
 UserDefaults.standard.set(pid, forKey:"HomePage_Fullname_ID")
 // rest of the code
}

方案二: 假设您有一个单独的自定义单元格,HomePage_TableViewCell, 在您的自定义单元格 HomePage_TableViewCell

中创建另一个 属性 'profile_id'

在 cellforRowAtIndexPath 中,设置相应的配置文件 ID。

mycell.profile_id = self.profile_ids[indexpath.row]

并将您的按钮操作移至自定义单元格内,以便您可以访问 profile_id 属性 作为 self.profile_id

@IBAction func resetClicked(sender: AnyObject) {
     UserDefaults.standard.set(self.profile_id, forKey:"HomePage_Fullname_ID")
       // rest of the code
}

你快到了。您只需要进行一些小的更改,您就可以访问该单元格中用户的 profile_id

  1. 将选择器Fullname_Click的签名改成这个

    func Fullname_Click(sender: UIButton)
    
  2. cellForRowAtIndexPath: 方法中添加这样的选择器

    button.addTarget(self, action: #selector(HomePageViewController.Fullname_Click(sender:)), for: .touchUpInside)
    
  3. Fullname_Click: 的实现中,现在您的按钮是 sender。使用它的标签从 profile_ids 数组中获取用户的 profile_id 像这样

    let profile_id = profile_ids[sender.tag]