【问题标题】:Double entry with UITableView使用 UITableView 进行双重输入
【发布时间】:2020-04-02 09:02:42
【问题描述】:

我的 ViewController 中有一个 UITableView。我想在我的文本字段中输入文本并单击按钮后,将文本添加到我的表格视图中。但是现在文本每次输入两次。

我的代码:

@IBAction func pressAddPlayer(_ sender: Any) {
        let text = self.spielerTextField.text!
        data.append(text)
        tableview.reloadData()
        tableview.endUpdates()
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
         let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!   
         let text = data[indexPath.row]  
         cell.textLabel?.text = text 
         return cell
}

TY

【问题讨论】:

  • 为按钮点击函数添加断点并检查它是否调用了两次

标签: ios arrays swift uitableview


【解决方案1】:

如果您已经在使用 reloadData(),则无需使用 endupdates。此外,我通过用简单的字符串替换文本字段文本来检查您的代码,它工作正常。那么您能否提供更多细节,因为问题主要不在这部分。

【讨论】:

    【解决方案2】:
    @IBAction func pressAddPlayer(_ sender: Any) {
            let text = self.spielerTextField.text!
            data.append(text)
            tableview.reloadData()
        }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
             let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as UITableViewCell   
             let text = data[indexPath.row]  
             cell.textLabel?.text = text 
             return cell
    }
    

    试试这个,效果很好。

    【讨论】:

      【解决方案3】:

      假设标识符已注册,此出列方法可确保返回单元格并正确调整其大小

      let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier", for: indexPath)
      

      另外,这里不需要使用 endUpdates

      tableview.reloadData()
      //tableview.endUpdates()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        相关资源
        最近更新 更多