繁体   English   中英

iOS Swift如何在TableView中单击时获取元素的值

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

我有一个通过Json获取数据的自定义TableView,在该tableView中有一个名为“ FullName”的Button。 该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号进行了硬编码,我希望将32号替换为属于该特定TableView Cell的profile_id的值。 在此代码中可以访问profile_id

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

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

解决方案1:假设每个名称都有一个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
}

解决方案2:假设您有一个单独的自定义单元格HomePage_TableViewCell,请在自定义单元格HomePage_TableViewCell中创建另一个属性'profile_id'

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

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

并将按钮动作移到自定义单元格中,以便您可以将self_profile_id作为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:的实现中Fullname_Click:现在,您可以将按钮作为sender 使用它的标签来获取profile_id从用户的profile_ids阵列这样的

     let profile_id = profile_ids[sender.tag] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM