2015-10-26 31 views
0

我如何使用for循環內cellForItemAtIndexPath我怎樣才能在tableView中使用循環swift

這裏是我的代碼,任何幫助嗎?

我想回到小區每個循環

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell:CellCollectionView = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CellCollectionView 
    for Restaurent1 in Resturent.Restaurants 
    { 
     var ResturentName = eachRestaurent.name 
     var ResturentDescrption = eachRestaurent.descrption 
     var ResturentId = eachRestaurent.id 

     cell.ResturentsName.text = ResturentName 
     cell.ResturentsDescrption.text = ResturentDescrption 
     cell.ResturentsId.text = String(ResturentId as! Int) 
    } 
    return cell 
} 
+0

你必須有2個拼寫Restaurant'的',這兩者都不是正確的.. – MTCoster

+0

在我的代碼不是,我寫了一個例子 –

回答

5

不要在cellForItemAtIndexPath使用循環。該循環已經內置到Cocoa中,該Cocoa調用您需要呈現的每個單元的cellForItemAtIndexPath實現。

此API遵循「拉」模型,而不是「推」。當需要的時候,表格視圖會從代碼中「拉出」數據,而不是一次性將所有數據「推送」到API中。這種方法的優點是「拉」API不會召回你需要的次數。例如,如果只有四家餐廳從100列表可見,你的方法將被調用四次,而不是100。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell:CellCollectionView = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CellCollectionView 
    let r = esturent.Restaurants[indexPath.row] 
    cell.ResturentsName.text = r.name 
    cell.ResturentsDescrption.text = r.descrption 
    cell.ResturentsId.text = String(r.id as! Int) 
    return cell 
} 
+0

Thx很多,你解決了我最大的問題:) :) –

+0

@ bsm-2000歡迎您!雖然Cocoa API的這個特殊部分並不直觀,但很容易學習:一旦你做了一次或兩次,就可以自然地開始跟蹤它,甚至可以構建自己的「拉」式API應用程序。 – dasblinkenlight

+0

@ bsm-2000嗨!如果此解決方案適合您,那麼請您接受它作爲正確答案。 – whyceewhite