【问题标题】:Tableview cells data is changing when I scroll vertically in swift iOS当我在 swift iOS 中垂直滚动时,Tableview 单元格数据正在发生变化
【发布时间】:2019-12-03 11:17:33
【问题描述】:

我开发了一个 iOS 应用程序,它有几个表格视图。如果我不滚动它工作正常,如果我滚动单元格内的表格视图数据数据正在改变,请让我在这里完美。 下面是第一个表的代码,其中包含 UISwitch 和文本。 参考请观看视频:https://drive.google.com/open?id=1hVHnAyGnQFrhvzLSoJjeMzG6wlfxoURm

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   if let d = self.data {
       return d.count
   }
   return  0

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    if let _ = cell {} else {
        cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    }
    if let d = self.data {
        cell?.textLabel?.text = d[indexPath.row]
        let switchView = UISwitch(frame: .zero)
        switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
        switchView.tag = indexPath.row // for detect which row switch Changed
        switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
        cell?.accessoryView = switchView

    }
    return cell!
}

func isFolderIsAdded(folderName:String) -> Bool{
    for   val in listOfSelectedFolder{
        if(folderName == val ){
            return true
        }
    }
    return false;
}

@objc func switchChanged(_ sender : UISwitch!){
    if let d = self.data {
        if(sender.isOn){
            self.delegate?.selectedSubFolder(name: d[sender.tag])
           } else {
            self.delegate?.deleteFilesFromFolder(folderName: d[sender.tag])
        }
    }
}

这是第二个表格代码,其中包含图像视图和文本。我创建了名为 TableViewCell 的自定义单元格。如需参考,请观看视频:https://drive.google.com/open?id=11snH5_henOadVCVqS9bL5SZRjcZF3vEU

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableViewContent.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! TableViewCell
    if let _ = contentModel[self.currentMode]{
        tempArr1 = appendFolderName(files: contentModel[self.currentMode]!, name: self.currentMode)!

    }
    if indexPath.row < tempArr1.count {
        cell.setupCellData(text: tempArr1[indexPath.row])
    }else{
        if let res = self.getFilesFromSubFolder(contentName: self.currentMode, folderName: self.SelectedFolder) {
            cell.setupCellData(text: res[indexPath.row - tempArr1.count] )

        }
    }
    let bgColorView = UIView()
    bgColorView.backgroundColor = UIColor.gray
    cell.selectedBackgroundView = bgColorView
    return cell
}

func setupCellData(text:String) {
    let temarr = text.components(separatedBy: "@")
    let str =  temarr.last?.capitalized
    let strq = temarr.first?.lowercased()
    let newstr = strq?.components(separatedBy: "-")
    let val = newstr?.last
    let content = val!.lowercased() + "@" +  str!
    self.ContentLabel.text = content
    if ((self.ContentLabel.text?.contains("pps"))!||(self.ContentLabel.text?.contains("pptx"))!||(self.ContentLabel.text?.contains("ppt"))!){
        imageData.image = #imageLiteral(resourceName: "table_Content_ppt")
    }else if ((self.ContentLabel.text?.contains("mp4"))! || (self.ContentLabel.text?.contains("mp3"))!){
        imageData.image = #imageLiteral(resourceName: "table_Content")
    }else if (self.ContentLabel.text?.contains("pdf"))!{
        imageData.image = #imageLiteral(resourceName: "pdf_content")
    }else if (self.ContentLabel.text?.contains("url"))!{
        imageData.image = #imageLiteral(resourceName: "url_content")
    }else if (self.ContentLabel.text?.contains("exe"))!{
        imageData.image = #imageLiteral(resourceName: "application_content")
    }else if (self.ContentLabel.text?.contains("doc"))!{
        imageData.image = #imageLiteral(resourceName: "word_content")
    }else if (self.ContentLabel.text?.contains("bat"))!{
        imageData.image = #imageLiteral(resourceName: "cmd")
    }
    else if (self.ContentLabel.text?.contains("lnk"))!{
        imageData.image = #imageLiteral(resourceName: "cmd")
    }
    else if ((self.ContentLabel.text?.contains("png"))! || (self.ContentLabel.text?.contains("jpg"))! || (self.ContentLabel.text?.contains("jpeg"))! || (self.ContentLabel.text?.contains("psd"))! || (self.ContentLabel.text?.contains("tiff"))! || (self.ContentLabel.text?.contains("gif"))!) {

        imageData.image = #imageLiteral(resourceName: "img")

    }else{
        imageData.image = nil

    }

}

我在 tableview 单元格类中添加了 prepareForReuse() 方法,但结果仍然是滚动后更改了相同的内容。

    override func prepareForReuse() {
    super.prepareForReuse()
    // Clear all content based views and their actions here
     imageData.image = nil
    ContentLabel.text = ""
}

【问题讨论】:

  • 在添加新数据之前需要清除重复使用的单元格内容。
  • 顺便说一句,您应该将 Xcode 更新到当前版本。
  • @LeoDabus 请帮助我了解我是 iOS 新手。谢谢
  • 清除它。如果是图像,则将其设置为 nil,等等,在您将单元格出列后
  • 我必须在 cellForRowAt indexPath 中清除??请提供更多想法,在这种情况下我需要清除。例如 UISwitch+Text 第一个表格滚动请发布您的答案。谢谢

标签: ios swift xcode uitableview swift4


【解决方案1】:

您必须更新switchChanged 中的listOfSelectedFolder 数组。

假设self.data 将被声明为非可选,将方法更改为

@objc func switchChanged(_ sender : UISwitch){
    let folderName = self.data[sender.tag]
    if sender.isOn {
        listOfSelectedFolder.append(folderName)
        self.delegate?.selectedSubFolder(name: folderName)
    } else {
       if let index = listOfSelectedFolder.index(of: folderName) {
          listOfSelectedFolder.remove(at: index)
       }
       self.delegate?.deleteFilesFromFolder(folderName: folderName)
    }
}

其他方法可以优化

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let folderName = self.data[indexPath.row]
    cell.textLabel?.text = folderName
    let switchView = UISwitch(frame: .zero)
    switchView.setOn(self.isFolderAdded(folderName: folderName), animated: true)
    switchView.tag = indexPath.row // for detect which row switch Changed
    switchView.addTarget(self, action: #selector(switchChanged), for: .valueChanged)
    cell.accessoryView = switchView
    return cell
}

func isFolderAdded(folderName: String) -> Bool{
    return listOfSelectedFolder.contains(folderName)
}

但是强烈建议使用自定义结构作为数据模型并添加isSelected 属性。并将listOfSelectedFolder 声明为一个集合。

【讨论】:

    【解决方案2】:

    把它放在你的单元格中

        override func prepareForReuse() {
            super.prepareForReuse()
            // Clear all content based views and their actions here
        }
    

    【讨论】:

    • 我在单元格类中添加了prepareforreuse。我有一个图像视图和标签如何重置它:imageData = nil ContentLabel = nil。这是正确的吗?
    • 不,你应该这样做:imageData.image = nil & contentLabel.text = ""
    • 出于性能原因,您应该只重置与内容无关的单元格属性,例如 alpha、编辑和选择状态。重用单元格时 tableView(_:cellForRowAt:) 中的表视图委托应始终重置所有内容 developer.apple.com/documentation/uikit/uitableviewcell/…
    • 这是错误的,大多数重置单元格中的任何内容都可能有所不同。诸如布局或颜色之类的东西或...在所有单元格中都相同的东西不需要重置。阅读:fluffy.es/solve-duplicated-cells
    • 我在单元格类中添加了 prepareForReuse() 但滚动后内容仍在变化 请检查我在问题末尾添加了代码。
    【解决方案3】:

    我之前也遇到过同样的问题,我尝试在 cellForRowAt 中添加 layoutIfNeeded() 并解决了问题。

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    
        if let _ = cell {} else {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        }
        if let d = self.data {
            cell?.textLabel?.text = d[indexPath.row]
            let switchView = UISwitch(frame: .zero)
            switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
            switchView.tag = indexPath.row // for detect which row switch Changed
            switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
            cell?.accessoryView = switchView
    cell?.layoutIfNeeded() <--- Add this
    
        }
        return cell!
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多