我有一個自定義的TableView,通過Json獲取數據,我有一個名爲「FullName」的tableView中的按鈕。該FullName顯然具有用戶名,但OnClick我想獲得與該特定TableViewCell相對應的「Profile_ID」,以便我可以保存它。我的代碼將有助於明確的東西IOS Swift如何獲取元素的值點擊TableView
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號屬於該特定TableView單元的profile_id的值。該PROFILE_ID是在此代碼
if let profile_id = Stream["profile_id"] as? String {
self.profile_ids.append(profile_id)
}
我能找到一種方法把它傳遞到FullName_Click功能訪問...
非常感謝該工作正常 – user1949387