【问题标题】:BackgroundView for section in the tableView表格视图中部分的背景视图
【发布时间】:2019-09-01 13:32:51
【问题描述】:

当我的TableView 为空时,我使用此功能添加背景视图。

func emptyTableViewMessage(with message: String) {
    let messageLabel: UILabel     = UILabel(frame: CGRect(x: todoTableView.bounds.size.width/2, y: todoTableView.bounds.size.height / 2 , width: todoTableView.bounds.size.width, height: todoTableView.bounds.size.height))
    messageLabel.text             = message
    messageLabel.textColor        = UIColor.gray
    messageLabel.font             = UIFont(name: "Open Sans", size: 15)
    messageLabel.textAlignment    = .center
    todoTableView.backgroundView = messageLabel
}

我叫它numberOfRowsInSection

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isSearching {
        if searchedData?.count == 0 {
            emptyTableViewMessage(with: "Not found")
        } else {
            emptyTableViewMessage.backgroundView = .none
        }

        return (searchedData?.count)!
    }

但是如果我有几个部分,例如其中一个是空的,我怎样才能在部分内添加这种背景视图(不是在标题中,因为我在标题中有不同的项目)

非常感谢

【问题讨论】:

  • numberOfRowsInSection 被多次调用。那不是调用emptyTableViewMessage 方法的地方。在实际加载数据时调用它,而不是从任何数据源方法中调用。

标签: swift tableview


【解决方案1】:

首先,您可以创建一个空单元格原型,当没有要显示的数据时使用这个原型。然后让我们修改您的emptyTableViewMessage 方法以返回UILabel

func emptyTableViewMessage(with message: String) -> UIView {
  let messageLabel: UILabel = UILabel(frame: CGRect(x: table.bounds.size.width/2, y: table.bounds.size.height / 2 , width: table.bounds.size.width, height: table.bounds.size.height))
  messageLabel.text = message
  messageLabel.textColor = UIColor.gray
  messageLabel.font = UIFont(name: "Open Sans", size: 15)
  messageLabel.textAlignment = .center
  return messageLabel
}

numberOfRowsInSection 中,当没有要显示的数据时,让我们返回 1(以显示 Not Found 文本)。如果有数据要显示,我们返回多少行。

guard let dataFound = searchedData?.count else { return 1 }
return dataFound > 0 ? dataFound : 1

最后在cellForRowAt 中,您根据searchData?.count 将适当的原型单元出列。

let notFound = searchData?.count > 0 ?? false
guard let cell = tableView.dequeueReusableCell(withIdentifier: notFound ? "NotFoundCellId" : "CellId") else { return UITableViewCell() }
if notFound {
  cell.backgroundView = emptyTableViewMessage(with: "Not Found")
} else {
  cell.textLabel?.text = countries[indexPath.row]
}

我很快创建了一个小项目来测试它,并且似乎工作正常,您可以在Github 进行检查。该项目没有管理生产代码应该如何处理的数据,搜索栏在 iPhone X 和更新版本的模拟器上不能很好地显示,等等;它只是一个关于如何在包含许多部分的表格视图中显示 Not Found 文本的快速示例,以便您了解如何操作。 部分截图:

无过滤器

按“ica”过滤

按“an”过滤

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2022-09-29
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多