【问题标题】:customize the first rows of UITableview in SWIFT在 SWIFT 中自定义 UITableview 的第一行
【发布时间】:2017-08-01 10:56:08
【问题描述】:

我正在尝试自定义 UITableView 的第一行。

我从具有商店名称和商店徽标的 API 获取 JSON 格式的数据。其中 5 家商店有设计背景,比顶部的其他单元格要大。

我可以遍历 JSON 并检查商店是否有设计,但我还不能做的是:

在数组中添加带有背景设计的商店

让它们首先出现在其他没有设计的商店之前。

这是我打算做的图片

【问题讨论】:

  • 您可以使用两个单元格并为两种类型的数据设置一个标志以检查要使用哪个单元格。
  • 你能解释更多吗?你到底需要什么代码?

标签: ios json swift uitableview


【解决方案1】:

首先,您的 Shop 类需要有一个带有背景图片的可选属性,例如:

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

只有这 5 家商店有背景图片,其余的 backgroundImage = nil

假设您已经从服务器获取并序列化了数据,让我们从过滤商店数组并重新排列它的顺序开始:

//"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

现在,您必须创建两个不同的自定义单元格(作为 XIB 或在 Storyboard 中) - 一个有背景,一个没有。 之后,只需像这样实现 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
}

希望对你有帮助:)

【讨论】:

  • 谢谢! numberOfRowsInSection 怎么样?我应该返回所有商店的数量吗?
  • @leo0019 这不是必要的方法
  • 什么意思?
  • 使用我建议的方法,表格视图有一个部分和两种单元格类型 - numberOfRowsInSection 应该等于 allShop.count
  • 对不起最后一个问题。如果 backgroundImageView 为 nill 怎么办?顶部单元格会是空的吗?还是第二个单元格覆盖了 backgroundImageView 单元格的空间?
【解决方案2】:

在您的表格视图中,您使用两个单元格。在这两个单元格中,一个单元格较大,并根据需要设置背景图像。在第二个单元格中使用较小的单元格。然后您在cellForRowAtIndexPath 方法中查看设计商店。如果 Shop 设计为 true,则在函数的 else 部分调用 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 当您从 JSON 中获得响应时,您将添加商店设计。如果您从商店设计中得到响应,则将其设置为真,否则为假
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多