我試圖自定義UITableView的第一行。在SWIFT中自定義UITableview的第一行
我從具有商店名稱和商店標識的API的JSON中獲取數據。 5個商店有一個設計的背景,應該比頂部的其他單元大。
我可以遍歷JSON和檢查,如果店內有一個設計,但我想不出但做的是:
追加背景設計的商店在陣列
使他們的其他店鋪之前,首先出現沒有設計。
這裏是什麼我打算做
我試圖自定義UITableView的第一行。在SWIFT中自定義UITableview的第一行
我從具有商店名稱和商店標識的API的JSON中獲取數據。 5個商店有一個設計的背景,應該比頂部的其他單元大。
我可以遍歷JSON和檢查,如果店內有一個設計,但我想不出但做的是:
追加背景設計的商店在陣列
使他們的其他店鋪之前,首先出現沒有設計。
這裏是什麼我打算做
所有店類首先需要有背景圖像的可選屬性,如:
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
}
希望它能幫助:)
在你的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
}
}
如果設計是一個空陣列呢? – leo0019
@ leo0019當您從JSON獲得響應時,添加店鋪設計。如果您從店鋪設計得到回覆,請確認其他明智的虛假 –
您可以使用兩種細胞,並設置標誌兩種類型的數據來檢查哪個小區使用。 –
你能解釋更多嗎?你需要什麼代碼? –