ios - 如何将循环的每个元素显示到表格行?

标签 ios swift uitableview loops

如何返回循环的每个元素。我的意思是我想显示这个循环的每个名称到行文本。它只返回最后一个元素。我怎样才能归还这一切?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)

        for last in lastnames {
            cellFullname.textLabel?.text = "\(last)"
        }
        return cellFullname
    }

最佳答案

您不需要循环来显示 UITableView 中的元素

假设您有一个姓氏数组:

var lastnames = ["....

并且您想将每个元素放入一个 UITableViewCell 中。两步:

  1. 定义您需要的细胞数量:

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
        return lastnames.count 
    }
    
  2. 使用以下名称更新 UITableView:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
    
    
        cellFullname.textLabel?.text = lastnames[indexPath.row]
    
        return cellFullname
    }
    

关于ios - 如何将循环的每个元素显示到表格行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40740135/

相关文章:

ios - 获取在按下时应用于 UIButton 背景图像的颜色

ios - Collection View 单元格内按钮的填充宽度

ios - 在 swift 中,当我的类有同名的子类时如何引用最顶层的类

swift - 使用 Alamofire result 和 present() 切换 View

swift - 在 swift 中动态地在 AlertController 中添加 tableview,如何?

ios - 使用搜索栏在结果的 UITableView 上显示原始 UITableView

swift - 将垂直 alpha 渐变应用于 UITableView

iOS 7 如何将 StatusBarStyle 从 DefaultContent 动画化为 LightContent

ios - NSZombie 已启用但仍然没有调试信息

iOS基于文本标签文本推送 View