首页 > 解决方案 > 如何在 Swift 中将默认文本添加到 TableView

问题描述

目前,我有这样的TableView设置:

override func viewDidLoad() {
        super.viewDidLoad()
        emulatorSettings()
        tableView.reloadData()
        self.reloadInputViews()
        tableView.dataSource = self
        tableView.register(UINib(nibName: K.cellNibName, bundle: nil), forCellReuseIdentifier: K.cellIdentifier)
        if let leftPostArray = userDefaults.array(forKey: fbLeftKey) as? [String]{
            votedLeftPosts = leftPostArray
        }
        if let rightPostArray = userDefaults.array(forKey: fbRightKey) as? [String]{
            votedRightPosts = rightPostArray
        }
        postQuery = Firestore.firestore()
            .collectionGroup("userPosts")
            .order(by: "postTime", descending: false)
            .limit(to: 3)
        
        loadMessages()
    }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // Trigger pagination when scrolled to last cell
        if (indexPath.row == posts.count - 1) {
            paginate()
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let post = posts[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath) as! PostCell
        cell.delegate = self
        
        postBrain.createPost(tableView, post, cell, self.storageRef)
        
        return cell
    }

我试图做到这一点,以便当表格视图为空时显示一个标签,指示用户做什么。我尝试在我的 Storyboard 中添加一个标签,但没有成功,我还尝试创建一个备用 .xib 文件,但也失败了。我一直找不到这方面的任何信息,有人可以帮助我吗?我知道我以前在android中做过这个,这不是Apple设计推荐的吗?

标签: iosswiftuitableview

解决方案


我会做以下事情:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//If there are no post you'll create a cell to put the instructions on how to proceed in.
 if posts.count == 0{ 
     return 1
 } else {
        return posts.count
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var post: PostStruct
        
        let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath) as! PostCell
        cell.delegate = self
        
        if posts.count == 0{
            cell.textLabel?.text = "Instructions"
        }else {
            post = posts[indexPath.row]
            postBrain.createPost(tableView, post, cell, self.storageRef)
            cell.textLabel?.text = ""
        }
        
        return cell
    }

这样,当您没有任何帖子(您的表格视图为空)时,您有 1 个可以放入说明的单元格。

如果要显示标签,我建议创建一个 UIView 自定义类,其中包含标签/文本视图,您将在其中写下所有说明,如果 posts.count == 0 则可以显示它。


推荐阅读