【问题标题】:How to make a table View with message showing if tableview empty?如何制作带有消息的表格视图,如果表格视图为空?
【发布时间】:2017-05-31 16:42:23
【问题描述】:

我正在构建一个 tableView,它在为空时显示一条消息。

我在这个问题上使用了非常有用的答案 (Handling an empty UITableView. Print a friendly message) 这让我想到了一个函数:

func emptyMessage(message:String, viewController:UITableViewController) {
        let VCSize = viewController.view.bounds.size
        let messageLabel = UILabel(frame: CGRect(x:0, y:0, width:VCSize.width, height:VCSize.height))
        messageLabel.text = message
        messageLabel.textColor = UIColor.black
        messageLabel.numberOfLines = 0
        messageLabel.textAlignment = .center;
        messageLabel.font = UIFont(name: "Futura", size: 15)
        messageLabel.sizeToFit()
        viewController.tableView.backgroundView = messageLabel;
        viewController.tableView.separatorStyle = .none;
    }

我可以像这样在每个表视图数据源中调用它:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if projects.count > 0 {
    return 1
} else {
    TableViewHelper.EmptyMessage("You don't have any projects yet.\nYou can create up to 10.", viewController: self)
    return 0
}
}

这会奏效。但是,我宁愿不必重复实现它,而是在数据源中有一个自定义 tableview 方法,询问您要添加什么消息。

我尝试过扩展 TableView 类或创建 tableView 的子类,但我认为这不是解决方案。相反,我认为解决方案是覆盖 UITableViewDataSource 协议,但我对协议和委派的了解还不够。

我希望我在正确的轨道上。澄清一下,我可以按照上面提到的方式做到这一点,但我正在尝试覆盖该功能以制作一个智能的解决方案,我不会重复自己。

【问题讨论】:

    标签: swift uitableview tableview


    【解决方案1】:

    有一个很好的图书馆:

    https://github.com/dzenbot/DZNEmptyDataSet

    这可用于所有类型的容器,如 UITableView、UICollectionView 等。

    符合一些DZNEmptyDataSetSourceDZNEmptyDataSetDelegate之后,就可以简单的实现这些功能了:

    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
            let str = "Empty Data."
            let attrs = [NSFontAttributeName: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)]
            return NSAttributedString(string: str, attributes: attrs)
        }
    
        func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
            let str = "Any Details about empty data."
            let attrs = [NSFontAttributeName: UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)]
            return NSAttributedString(string: str, attributes: attrs)
        }
    

    除此之外,您还可以添加一个按钮来执行一些操作。有关更多功能,请参阅库。

    【讨论】:

    • 真的很感激这一点,我看过图书馆,这会奏效。我没有在问题中指定,所以你不会知道,但我没有去图书馆的原因是我想了解如何做到这一点背后的理论。我将尝试阅读 github 文件,看看他们是如何做到的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多