2017-08-01 36 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获得响应时,添加店铺设计。如果您从店铺设计得到回复,请确认其他明智的虚假 –

相关问题