user1949387 user1949387 - 1 month ago 5
Swift Question

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

I have a custom TableView that gets data via Json, I have a Button in that tableView named "FullName" . That FullName obviously has user's name but OnClick I would like to get the "Profile_ID" that corresponds to that particular TableViewCell so that I can save it. My code will help clear things up

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


}


}


The main issue is with this piece of code

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)
}


Notice I hard coded the number 32 what I would like is to replace the number 32 with the value of profile_id that belongs to that particular TableView Cell . The profile_id is accessible in this code

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


I just can find a way to pass it into the FullName_Click function ...

Answer

You are almost there. You just need to make a couple of small changes and you'll be able to access the profile_id of the user in that cell.

  1. Change the signature of the selector Fullname_Click to this

    func Fullname_Click(sender: UIButton)
    
  2. In cellForRowAtIndexPath: method add the selector like this

    button.addTarget(self, action: #selector(HomePageViewController.Fullname_Click(sender:)), for: .touchUpInside)
    
  3. In the implemetation of Fullname_Click: now you have your button as sender. Use its tag to get the profile_id of the user from profile_ids array like this

    let profile_id = profile_ids[sender.tag]