Is it possible to assign two values to a cell in a UITableView?
I have a json file that is structured like this:
{
"band": [
"Name": "The Kooks",
"id": "1258"
]
}
I can get the label to display in the cell and pass it to a new view controller, but how do I also assign the id so that I can pass that too?
I am new to swift so please dont eat me.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
items is empty, so I get it like so:
Alamofire.request(.GET, testurl, parameters: ["bandName": bandName])
.responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
for (_,bands) in json {
for (_,bname) in bands {
let bandName = bname["Name"].stringValue
print(bandName)
self.items.append(bandName)
self.tableView.reloadData()
}
}
}
case .Failure(let error):
print(error)
}
}
答案 0 :(得分:1)
你不应该将bname Dictionary中的每个值都添加到self.items中。 尝试将bname添加到self.items,代码:
Alamofire.request(.GET, testurl, parameters: ["bandName": bandName])
.responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
for (_,bands) in json {
for (_,bname) in bands {
self.items.append(bname)
self.tableView.reloadData()
}
}
}
case .Failure(let error):
print(error)
}
}
并在cellForRowAtIndexPath中使用它: func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) - > UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
if let dic = self.items[indexPath.row] as? NSDictionary{
if let id = dic["id"] as? String{
cell.idLabel.text = id
}
if let name = dic["Name"] as? String{
cell.nameLabel.text = name
}
}
return cell
}
答案 1 :(得分:0)
使用这些属性创建类或模型,并在对象中赋值保持NSarray中的对象,该对象使用选定的索引路径从数据源获取数据源,并使用prepareForSegue将对象传递给新的viewcontroller。