我正在一个控制器中使用swift开发一个应用程序,同时使用了集合视图和表视图。集合视图位于控制器的顶部,该控制器水平滚动并包含近10个单元格,而表视图则保持在集合视图的下方。已经将json(api)数据传递到集合和表视图中,现在我必须调用另一个json数据(另一个api),该数据是第一个json数据之前的子类别,然后如果我轻按集合视图的单元格,则应调用第二个api并再次重新加载表格视图以显示第二个api数据...该怎么做?
func jsonParsingFromURL () {
Alamofire.request(.POST, "http://something.com", parameters: nil, encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
// print(res)
// print(data)
let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(dataString)
self.startParsing(data!)
self.collecStartParsing(data!)
}
}
func startParsing(data :NSData)
{
let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
for i in 0 ..< (dict.valueForKey("subcategory") as! NSArray).count
{
arrDict.addObject((dict.valueForKey("subcategory") as! NSArray) .objectAtIndex(i))
}
SecondTableView.reloadData()
}
func collecStartParsing(data :NSData){
let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
for i in 0 ..< (dict.valueForKey("subcategory_icons") as! NSArray).count
{
collectionitems.addObject((dict.valueForKey("subcategory_icons") as! NSArray) .objectAtIndex(i))
}
FirstCollectionView.reloadData()
}
我的表和集合视图的数据源方法:
func tableview cell for row at indexpath {
let cell = tableView.dequeueReusableCellWithIdentifier("SegueCell") as! SecondTableViewCell
let strTitle:NSString = arrDict[indexPath.row] .valueForKey("adtitle") as! NSString
cell.TitleLabel.text = strTitle as String
return cell
集合视图:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FirstCollectionView", forIndexPath: indexPath) as! FirstCollectionViewCell
let strTitle:NSString = collectionitems[indexPath.item] .valueForKey("subcategoryname") as! NSString
cell.TitleLabel.text = strTitle as String
return cell
它有助于调用第一个api并传递数据。现在我已经为另一个api编写了不同的功能:
func jsonParsingForIcon () {
Alamofire.request(.POST, "http://www.mysecondapi.com", nil, encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
// print(res)
// print(data)
let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(dataString)
}
}
现在,两个json(api)都具有相同的键值对,通过点击collection view的单元格,应调用第二个api函数并根据第二个api json数据重新加载我的表视图。
比斯塔先生的答案应该被接受。
只是我们需要删除数组,即myarray.removeallobjects()
基本骨架:
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let category = categoryArray[indexPath.row]
myAPI(category.id)
}
func myAPI(categoryID:String) {
//pass the categoryID into the parameter to get corresponding data.
callAPI {
if success {
tableArray = data from server
tableView.reloadData()
} else {
//some error occurred
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句