我如何在tableView swift中使用循环

bsm*_*000 0 loops tableview swift

我如何在cellForItemAtIndexPath中使用for循环

这是我的代码,任何帮助?

我希望每个循环返回单元格

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
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

不要使用循环cellForItemAtIndexPath.该循环已内置于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
}
Run Code Online (Sandbox Code Playgroud)