2017-08-01 34 views
0

我試圖自定義UITableView的第一行。在SWIFT中自定義UITableview的第一行

我從具有商店名稱和商店標識的API的JSON中獲取數據。 5個商店有一個設計的背景,應該比頂部的其他單元大。

我可以遍歷JSON和檢查,如果店內有一個設計,但我想不出但做的是:

追加背景設計的商店在陣列

使他們的其他店鋪之前,首先出現沒有設計。

這裏是什麼我打算做

enter image description here

shops without

+4

您可以使用兩種細胞,並設置標誌兩種類型的數據來檢查哪個小區使用。 –

+0

你能解釋更多嗎?你需要什麼代碼? –

回答

1

所有類首先需要有背景圖像的可選屬性,如:

class Shop { 
    ... 
    var backgroundImage: UIImage? 
    ... 
} 

只有在那5個店鋪有背景圖片,其餘的都是backgroundImage =無

假設你已經獲取和序列化從服務器的數據,讓我們從過濾的商店陣列,並重新安排它開始的命令:

//"fetchedShops" is array of serialized shops: [Shop]() 
let shopsWithBackgroundImage = fetchedShops.filter({ $0.backgroundImg != nil }) 
let showWithNoImage = shops.filter({ $0.backgroundImg == nil } 
let allShops = shopsWithBackgroundImage + showWithNoImage 

現在,你必須創建兩個不同的自定義的細胞(如XIBs或故事板) - 有背景和沒有的背景。 之後,只需執行的cellForRowAtIndexPath這樣的:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
let shop = allShops[indexPath.row] 
if shop.backgroundImage != nil { 
    //"shop" has background image - use custom cell with background image 
    let cell = tableView.dequeueReusableCell(withReuseIdentifier: cellWithBackgroundImageID, for: indexPath) as! CellWithBackground 
    cell.backgroundImageView.image = shop.backgroundImage 

    //other cell's config 

    return cell 
} 
//"shop" has no backgroundImage - let's use normal cell 
let cell = tableView.dequeueReusableCell(withReuseIdentifier: normalShopCellID, for: indexPath) as! NormalShopCell 

//other cell's config 

return cell 
} 

希望它能幫助:)

+0

謝謝!那麼'numberOfRowsInSection'怎麼樣?我應該歸還所有商店的數量嗎? – leo0019

+0

@ leo0019這不是必須的方法 –

+0

你是什麼意思? – leo0019

1

在你的tableview您使用兩個單元的圖像。在這兩個單元格中,一個單元格更大,並根據需要設置背景圖像。在第二個單元中使用較小的單元。然後你檢查cellForRowAtIndexPath方法的設計店。如果商店設計是真的,那麼在函數的其他部分調用First Cell或其他。

示例代碼...

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    if self.design[indexPath.row] == true { 
     let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "firstCustomCell") 
     //set the data here 
     return cell 
    } 
    else { 
     let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "thirdCustomCell") 
     //set the data here 
     return cell 
    } 
} 
+0

如果設計是一個空陣列呢? – leo0019

+0

@ leo0019當您從JSON獲得響應時,添加店鋪設計。如果您從店鋪設計得到回覆,請確認其他明智的虛假 –

相關問題