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

标签 ios swift uitableview swift3 nsuserdefaults

我有一个通过 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 进行了硬编码,我希望将数字 32 替换为属于该特定 TableView Cell 的 profile_id 的值。在此代码中可以访问 profile_id

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

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

最佳答案

你快到了。您只需进行一些小的更改,就可以访问该单元格中用户的 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]
    

关于IOS Swift 如何在 TableView 中单击时获取元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40431858/

相关文章:

ios - PFRelation 从 PFRelation 中删除一个对象,而不是全部

iOS 在突出显示或选中时将按钮文本更改为粗体

ios - 如何在 TWTweetComposeViewController 中设置文本光标的位置?

swift - 更新到 Xcode 8 beta 6 后,关联枚举中丢失了 CKErrorCode 和 .rawValue

swift - 可编码的失败初始化器

swift - iOS11中有没有办法指定UIContextualAction的宽度?

ios - SwiftUI - 初始化前使用的变量 'self.fetchRequest'

ios - 使用NSDateFormatter将NSString解析为NSDate

ios - Swift 中是否有#ifdef 来区分Xcode 6.4 和Xcode 7 beta?

iphone - 使用 "inserted"行初始化 UITableView