在swift 4

时间:2018-02-09 07:11:57

标签: ios uitableview sorting

我在tableview的单元格上有三个标签。一个显示名称,第二个显示大小,第三个显示日期。我有三个参数来排序tableview的单元格,即名称,大小和日期。

我希望当我点击名称时,单元格会按照升序显示其名称,当我点击大小时,它应按照大小按升序排列,当我点击日期时,它应按照日期按升序排列并且其余两个标签应根据各自的名称,大小或日期排列。

我只能对名字,尺寸和尺寸进行排序。 date.using以下代码:

@IBAction func indexChanged(_ sender: UISegmentedControl) {
        if(itemArray.count>1){
        switch sender.selectedSegmentIndex {
        case 0:
            sortedNameArray = fileNameArray.sorted {$0.localizedStandardCompare($1) == .orderedAscending}

            sortParameter = "name"
            mediaTableView.reloadData()
            print("sorted name array",sortedNameArray)
        break
        case 1:
            sortedSizeArray = fileSizeArray.sorted {$0.localizedStandardCompare($1) == .orderedAscending}
            print("sorted Size array",sortedSizeArray)
           sortParameter = "size"
           mediaTableView.reloadData()
           print("1")
        case 2:
             sortedDateArray = dateArray.sorted(by: { $0.compare($1) == .orderedAscending })
             print("sorted date array",sortedDateArray)
            sortParameter = "date"
            mediaTableView.reloadData()
        default:
            break;
        }
        }

    }
}

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

        let cell = tableView.dequeueReusableCell(withIdentifier:"mediaCell",for:IndexPath) as! MediaCustomCell
        if(sortParameter == ""){
            if(itemArray.count>0){
                let urlString: String = itemArray[IndexPath.row].absoluteString
                let fileName = (urlString as NSString).lastPathComponent
                fileNameArray.append(fileName)
                do {
                    //size
                    let resources = try itemArray[IndexPath.row].resourceValues(forKeys:[.fileSizeKey])
                    let fileSize = resources.fileSize!
                    let fileSizeValue = self.transformedValue(value: fileSize)
                    cell.fileSizeLbl.text = String.init(format:"%@",fileSizeValue as! CVarArg)
                    fileSizeArray.append(cell.fileSizeLbl.text!)

                    //date
                    let fileCreatedDate = try itemArray[IndexPath.row].resourceValues(forKeys:[.creationDateKey])

                    let dateCreated = fileCreatedDate.creationDate
                    dateArray.append(dateCreated!)

                    cell.createdDateLbl.text = String.init(format:"%@",dateCreated! as CVarArg)

                    print ("filesize",fileSizeValue)
                } catch {
                    print("Error: \(error)")
                }
                cell.itemLbl.text = fileName
            }
        }

         //when it gets sorted on the basis of name
        else if(sortParameter == "name"){

            //name
            cell.itemLbl.text=sortedNameArray[IndexPath.row]
            let fileManager = FileManager.default
            let documentsURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
            let fullpath = documentsURL.appendingPathComponent(sortedNameArray[IndexPath.row])
            //size
            do{
            let resources = try fullpath.resourceValues(forKeys:[.fileSizeKey])
            let fileSize = resources.fileSize!
            let fileSizeValue = self.transformedValue(value: fileSize)
            cell.fileSizeLbl.text = String.init(format:"%@",fileSizeValue as! CVarArg)
            }catch{
                print("error")
            }

            //date
             let path = documentsURL.appendingPathComponent(sortedNameArray[IndexPath.row])
            do{
            let fileCreatedDate = try path.resourceValues(forKeys:[.creationDateKey])
            let dateCreated = fileCreatedDate.creationDate
            cell.createdDateLbl.text = String.init(format:"%@",dateCreated! as CVarArg)
            }
            catch{
                print("error")
            }
         }


        else if(sortParameter == "size"){
           cell.fileSizeLbl.text = sortedSizeArray[IndexPath.row]





        }
        else if(sortParameter == "date"){
            cell.createdDateLbl.text = String.init(format:"%@",sortedDateArray[IndexPath.row] as CVarArg)
        }
        return cell
    }
}



func checkFileForExistence(){
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
        do {
            let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            print("file urls",fileURLs)
            for files in fileURLs{
                if files.absoluteString.contains(".mp4")||files.absoluteString.contains(".mov")||files.absoluteString.contains(".MOV")||files.absoluteString.contains(".m4a"){
                    itemArray.append(files)
                }
            }
        } catch {
            print("Error while enumerating files", (error.localizedDescription))
        }
    }

问题: - 我可以根据名称,大小或日期对它们进行排序,但其余的两个标签显示过时的数据。我的意思是,如果现在nameLabel1首先出现,它仍然显示label2的大小和标签3的日期。 我太新了,不能迅速。请帮我解决这个问题。非常感谢任何帮助或建议。谢谢!

1 个答案:

答案 0 :(得分:1)

您应该为数据使用Model结构,而不是创建3个不同的数组。

struct File
{
  var name:String!
  var size:String!
  var date:Date!
}

然后使用创建的struct类型创建两个数组。

  var allFileDetails:[File]!
  var sortedFileDetails:[File]!

您可以在段控制中更改索引时对数组进行排序

@IBAction func indexChanged(_ sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
    case 0:
      sortedFileDetails = allFileDetails.sorted(by: { $0.name < $1.name })
    case 1:
      sortedFileDetails = allFileDetails.sorted(by: { $0.size < $1.size })
    case 2:
      sortedFileDetails = allFileDetails.sorted(by: { $0.date < $1.date })
    default:
      break;
    }
    self.tableView.reloadData()
  }

像这样更新您的checkFileForExistence方法。

func checkFileForExistence(){
    let fileManager = FileManager.default
    let documentsURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
    do {
      let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
      print("file urls",fileURLs)
      for files in fileURLs{
        if files.absoluteString.contains(".mp4")||files.absoluteString.contains(".mov")||files.absoluteString.contains(".MOV")||files.absoluteString.contains(".m4a")
        {
          do {
            //name
            let fileName = (files.absoluteString as NSString).lastPathComponent
            //size
            let resources = try files.resourceValues(forKeys:[.fileSizeKey])
            let fileSize = resources.fileSize!
            let fileSizeValue = self.transformedValue(value: fileSize)
            let fileSizeStr = String.init(format:"%@",fileSizeValue as! CVarArg)
            //date
            let fileCreatedDate = try files.resourceValues(forKeys:[.creationDateKey])
            let dateCreated = fileCreatedDate.creationDate
            self.allFileDetails = [File(name: fileName, size: fileSizeStr, date: dateCreated)]
          } catch {
            print("Error: \(error)")
          }
        }
      }
    } catch {
      print("Error while enumerating files", (error.localizedDescription))
    }
  }

并在sortedFileDetails.countnumberOfRowsInSection方法中使用cellForRowAt

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sortedFileDetails.count
  }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell = tableView.dequeueReusableCell(withIdentifier:"mediaCell",for:IndexPath) as! MediaCustomCell
   cell.itemLbl.text = sortedFileDetails[indexPath.row].name
   cell.fileSizeLbl.text = sortedFileDetails[indexPath.row].size
   cell.createdDateLbl.text = sortedFileDetails[indexPath.row].date.description
   return cell
}