Ios 从下拉列表中选择两个文件以在swift的UITableView上显示时出错

Ios 从下拉列表中选择两个文件以在swift的UITableView上显示时出错,ios,swift,xcode,uitableview,Ios,Swift,Xcode,Uitableview,我的viewcontroller中有两个tableview和两个下拉菜单,我从中为每个tableview选择一个csv文件以显示其内容。 我得到一个索引超出范围的错误。调试后,我知道如果两个文件的行数相等,则不会显示任何错误。 如何解决此错误,因为我有许多csv文件,其中可能包含的数据量不相等 import UIKit import DropDown class CompareFilesViewController: UIViewController,UITableViewDelegate, U

我的viewcontroller中有两个tableview和两个下拉菜单,我从中为每个tableview选择一个csv文件以显示其内容。 我得到一个索引超出范围的错误。调试后,我知道如果两个文件的行数相等,则不会显示任何错误。 如何解决此错误,因为我有许多csv文件,其中可能包含的数据量不相等

import UIKit
import DropDown
class CompareFilesViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {



@IBOutlet weak var DropDownView: UIView!
@IBOutlet weak var DropDownView2: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableView2: UITableView!
@IBOutlet weak var selectedFile_lbl: UILabel!
@IBOutlet weak var selectedFile_lbl2: UILabel!

var  filesDropDown = DropDown()
var filesDropDown2 = DropDown()

var files1 = [String]()
var files2 = [String]()

var files1Data = [String]()
var files2Data = [String]()

var refreshControl: UIRefreshControl?

var dropDownFlag = false
var dropDownFlag1 = false

var filename: String?
var filename1: String?

override func viewDidLoad() {
    super.viewDidLoad()
    
   var files = [String]()
    files1Data.append("Select Files from drop down")
    files2Data.append("Select Files from drop down")
    // Do any additional setup after loading the view.
  let fm = FileManager.default
         let path = getDocumentsDirectory()
         
         do{
             
             let items = try fm.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)
             let onlyFileNames = items.filter{ !$0.hasDirectoryPath }
             let onlyFileNamesStr = onlyFileNames.map { $0.lastPathComponent }
             files.append(contentsOf: onlyFileNamesStr)
               //getting different file names 
               for index in 0..<files.count{
                
                if files[0].components(separatedBy: "_")[0] == files[index].components(separatedBy: "_")[0]{
                  print(true)
                    files1.insert(files[index], at: 0)
                }
                else{
                    print(false)
                        files2.insert(files[index], at: 0)
                }
                
                
            }
             print("file names\(onlyFileNamesStr)")
            
            
         }
         catch
         {
             print(error)
             
         }

    setDropDown1()
    setDropDown2()
    
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    
    tableView2.delegate = self
    tableView2.dataSource = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell2")
    

}



@IBAction func DropDownViewTapped(_ sender: Any) {
          
    filesDropDown.show()
}

@IBAction func DropDownView2Tapped(_ sender: Any) {
      
    filesDropDown2.show()
}

@IBAction func compareFiles(_ sender: Any) {
   
    files2Data.removeAll()
    files1Data.removeAll()
    files2Data.insert(contentsOf: self.getSelectedFileContent(fileName: filename1!), at: 0)
    files1Data.insert(contentsOf: self.getSelectedFileContent(fileName: filename!), at: 0)
    
    tableView.reloadData()
    tableView2.reloadData()    
}
//for right dropdown
func setDropDown1() {

    
  filesDropDown.textFont = UIFont.systemFont(ofSize: 10)
    filesDropDown.textColor = .blue
    filesDropDown.dataSource = files1
     filesDropDown.anchorView = DropDownView2
    filesDropDown.selectionAction = { index, title in
                     
        self.dropDownFlag = true
                     
                     print("index: \(index), title: \(title)")
        self.filename = title
        self.selectedFile_lbl2.text = self.filename
                        
        // self.files1Data.insert(contentsOf: self.getSelectedFileContent(fileName: title), at: 0)
        //self.tableView2.reloadData()
                 }
   
}
//for left drop down
func setDropDown2(){
    
    filesDropDown2.textFont = UIFont.systemFont(ofSize: 10)

        filesDropDown2.dataSource = files2
        filesDropDown2.anchorView = DropDownView
    
        filesDropDown2.selectionAction = { index, title in
                          
            self.dropDownFlag1 = true
                          
                          print("index: \(index), title: \(title)")
            self.filename1 = title
            self.selectedFile_lbl.text =  self.filename1
 
                      }
  
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      
    var count: Int?
    
    if tableView == self.tableView{
        count = files1Data.count
        print(count as Any)
    }
    if tableView == self.tableView2{
        count = files2Data.count
        print(count as Any)
    }
    print(count as Any)
    return count!
  }
  
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
var cell:UITableViewCell?

    if tableView == self.tableView{
            cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell!.textLabel?.text = files2Data[indexPath.row]//error: index out of range
            cell!.textLabel!.numberOfLines = 0
            // cell!.textLabel?.adjustsFontSizeToFitWidth = true
            cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
        }
        if tableView == self.tableView2{
            cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
            cell!.textLabel?.text = files1Data[indexPath.row]//error: index out of range
            cell!.textLabel!.numberOfLines = 0
            // cell!.textLabel?.adjustsFontSizeToFitWidth = true
            cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
        }

return cell!
}

func getSelectedFileContent(fileName: String) -> [String] {
    var contentsArray = [String]()
    let fm = FileManager.default
    let destURL = getDocumentsDirectory().appendingPathComponent(fileName)
    do {
        if fm.fileExists(atPath: destURL.path) {
                         let contents = try String(contentsOf: destURL)
            contentsArray = contents.components(separatedBy: "\n")
            print(contents)
        }
    } catch {
        print("File copy failed.")
    }

 return contentsArray
}

}
导入UIKit
导入下拉列表
类CompareFileViewController:UIViewController、UITableViewDelegate、UITableViewDataSource{
@IBV弱var下拉视图:UIView!
@IBOUTLE弱var下拉视图2:UIView!
@IBVAR表格视图:UITableView!
@IBVAR表格视图2:UITableView!
@IBOUTLE弱var SELECTED文件\u lbl:UILabel!
@IBOUTLE弱var SELECTED文件\u lbl2:UILabel!
var filesDropDown=DropDown()
var filesDropDown2=DropDown()
变量files1=[String]()
var files2=[String]()
var files1Data=[String]()
var files2Data=[String]()
var refreshControl:UIRefreshControl?
var dropDownFlag=false
var dropDownFlag1=false
变量文件名:字符串?
var filename1:字符串?
重写func viewDidLoad(){
super.viewDidLoad()
var文件=[String]()
files1Data.append(“从下拉列表中选择文件”)
追加(“从下拉列表中选择文件”)
//加载视图后执行任何其他设置。
设fm=FileManager.default
让path=getDocumentsDirectory()
做{
let items=try fm.contentsOfDirectory(at:path,includingPropertiesForKeys:nil)
让onlyFileNames=items.filter{!$0.hasDirectoryPath}
让onlyFileNamesStr=onlyFileNames.map{$0.lastPathComponent}
files.append(contentsOf:onlyFileNamesStr)
//获取不同的文件名
对于0..Int中的索引{
变量计数:Int?
如果tableView==self.tableView{
count=files1Data.count
打印(按任何方式计算)
}
如果tableView==self.tableView2{
count=files2Data.count
打印(按任何方式计算)
}
打印(按任何方式计算)
返回计数!
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
变量单元格:UITableViewCell?
如果tableView==self.tableView{
cell=tableView.dequeueReusableCell(带有标识符:“cell”,用于:indexath)
cell!.textlab?.text=files2Data[indexath.row]//错误:索引超出范围
单元格!.textLabel!.numberOfLines=0
//单元格!.textLabel?.adjustsFontSizeToFitWidth=true
cell!.textLabel?.font=UIFont(名称:“Arial”,大小:10.0)
}
如果tableView==self.tableView2{
cell=tableView.dequeueReusableCell(标识符为“Cell2”,表示:indexPath)
cell!.textlab?.text=files1Data[indexath.row]//错误:索引超出范围
单元格!.textLabel!.numberOfLines=0
//单元格!.textLabel?.adjustsFontSizeToFitWidth=true
cell!.textLabel?.font=UIFont(名称:“Arial”,大小:10.0)
}
返回单元!
}
func getSelectedFileContent(文件名:字符串)->[字符串]{
var contentsArray=[String]()
设fm=FileManager.default
让destURL=getDocumentsDirectory()。追加路径组件(文件名)
做{
如果fm.fileExists(atPath:destURL.path){
let contents=try字符串(contentsOf:destURL)
contentsArray=contents.components(以“\n”分隔)
印刷品(目录)
}
}抓住{
打印(“文件复制失败”)
}
返回内容数组
}
}
我已尝试添加RefreshControl,但这不起作用。 对于下拉列表,我使用了AssistoLab库

我真正想要的是选择csv文件,并在单击按钮时将其显示到TableView以进行比较
有没有更好的解决办法,我可以用?

您可以按以下方式修改您的条件:

    if tableView == self.tableView {
    
    if files2Data.count <= indexPath.row {
        // Your code
    }else{
       return UITableViewCell()
    }
  }
如果tableView==self.tableView{

如果files2Data.count我不知道为什么,但是在重构我的代码之后,它就像我想要的那样工作。我只是添加了两个按钮,在从下拉菜单中选择后,两个文件都显示出来

import UIKit
import DropDown
class DemoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


@IBOutlet weak var topDropDownView: UIView!
@IBOutlet weak var bottomDropDownView: UIView!

@IBOutlet weak var selectFile_lbl1: UILabel!
@IBOutlet weak var selectFile_lbl2: UILabel!

@IBOutlet weak var tableView1: UITableView!
@IBOutlet weak var tableView2: UITableView!

var data1 = [String]()
var data2 = [String]()

var topDropDown = DropDown()
var bottomDropDown = DropDown()

var files1 = [String]()
var files2 = [String]()

var filename1 = ""
var filename2 = ""

override func viewDidLoad() {
    super.viewDidLoad()
    
    getFileNames()
    
    setDropDown1()
    setDropDown2()
    
    tableView1.delegate = self
    tableView2.delegate = self
    tableView1.dataSource = self
    tableView2.dataSource = self
    
     tableView1.register(UITableViewCell.self, forCellReuseIdentifier: "cell1")
     tableView2.register(UITableViewCell.self, forCellReuseIdentifier: "cell2")

}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
}
*/
@IBAction func button1(_ sender: Any) {
    data1.removeAll()
    data1.append(contentsOf: getSelectedFileContent(fileName: filename1))
    tableView1.reloadData()
    
   }
@IBAction func button2(_ sender: Any) {
    data2.removeAll()
    data2.append(contentsOf: getSelectedFileContent(fileName: filename2))
           tableView2.reloadData()
}

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count: Int?

      if tableView == self.tableView1{
          count = data1.count
        print(count as Any)
      }
      if tableView == self.tableView2{
          count = data2.count
        print(count as Any)
      }
print(count as Any)
      return count!
 }
 
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     var cell:UITableViewCell?
     
         if tableView == self.tableView1{
                 cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
                 cell!.textLabel?.text = data1[indexPath.row]
                 cell!.textLabel!.numberOfLines = 0
                 // cell!.textLabel?.adjustsFontSizeToFitWidth = true
                 cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
             }
             if tableView == self.tableView2{
                 cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
                 cell!.textLabel?.text = data2[indexPath.row]
                 cell!.textLabel!.numberOfLines = 0
                 // cell!.textLabel?.adjustsFontSizeToFitWidth = true
                 cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
             }
     
     return cell!
 }

 
    func getSelectedFileContent(fileName: String) -> [String] {
        var contentsArray = [String]()
        let fm = FileManager.default
        let destURL = getDocumentsDirectory().appendingPathComponent(fileName)
        do {
            if fm.fileExists(atPath: destURL.path) {
                             let contents = try String(contentsOf: destURL)
                contentsArray = contents.components(separatedBy: "\n")
                print(contents)
            }
        } catch {
            print("File copy failed.")
        }

     return contentsArray
    }


@IBAction func topDropDownView_tapped(_ sender: Any) {
    topDropDown.show()
}

@IBAction func bottomDropDownView_tapped(_ sender: Any) {
    bottomDropDown.show()
}

func getFileNames(){
    
    var files = [String]()
    let fm = FileManager.default
    let path = getDocumentsDirectory()
    
    do{
        let items = try fm.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)
        let onlyFileNames = items.filter{ !$0.hasDirectoryPath }
        let onlyFileNamesStr = onlyFileNames.map { $0.lastPathComponent }
        
        files.append(contentsOf: onlyFileNamesStr)
        
        for index in 0..<files.count{
            
            if files[0].components(separatedBy: "_")[0] == files[index].components(separatedBy: "_")[0]{
                print(true)
                files1.insert(files[index], at: 0)
            }
            else{
                print(false)
                files2.insert(files[index], at: 0)
            }
        }
        print("file names\(onlyFileNamesStr)")
    }
    catch
    {
        print(error)
        
    }
}

//for right dropdown
func setDropDown1() {

    
  topDropDown.textFont = UIFont.systemFont(ofSize: 10)
    topDropDown.textColor = .blue
    topDropDown.dataSource = files1
     topDropDown.anchorView = topDropDownView
    topDropDown.selectionAction = { index, title in
                        
        print("index: \(index), title: \(title)")
        self.filename1 = title
        self.selectFile_lbl1.text = self.filename1
                        
        // self.files1Data.insert(contentsOf: self.getSelectedFileContent(fileName: title), at: 0)
        //self.tableView2.reloadData()
                 }
   
}
//for left drop down
func setDropDown2(){
    
    bottomDropDown.textFont = UIFont.systemFont(ofSize: 10)

        bottomDropDown.dataSource = files2
        bottomDropDown.anchorView = bottomDropDownView
    
        bottomDropDown.selectionAction = { index, title in
                          
            
                          
                          print("index: \(index), title: \(title)")
            self.filename2 = title
            self.selectFile_lbl2.text =  self.filename2
            //self.files2Data.insert(contentsOf: self.getSelectedFileContent(fileName: title), at: 0)
           // self.tableView2.reloadData()
                      }
  
}
导入UIKit
导入下拉列表
类DemoViewController:UIViewController、UITableViewDelegate、UITableViewDataSource{
@IBOutlet弱var topDropDownView:UIView!
@IBMOutlet弱var bottomDropDownView:UIView!
@IBOutlet弱var选择文件\u lbl1:UILabel!
@IBOutlet弱var选择文件\u lbl2:UILabel!
@IBVAR表格视图1:UITableView!
@IBVAR表格视图2:UITableView!
变量data1=[String]()
变量data2=[String]()
var topDropDown=DropDown()
var bottomDropDown=DropDown()
变量files1=[String]()
var files2=[String]()
var filename1=“”
var filename2=“”
重写func viewDidLoad(){
super.viewDidLoad()
getFileNames()
setDropDown1()
setDropDown2()
tableView1.delegate=self
tableView2.delegate=self
tableView1.dataSource=self
tableView2.dataSource=self
tableView1.寄存器(UITableViewCell.self,强制重用标识符:“cell1”)
tableView2.寄存器(UITableViewCell.self,强制重用标识符:“cell2”)
}
/*
//标记:-导航
//在基于故事板的应用程序中,您通常需要在导航之前做一些准备
覆盖功能准备(对于segue:UIStoryboardSegue,发送方:有吗?){
//使用segue.destination获取新的视图控制器。
//将选定对象传递给新的视图控制器。
}
*/
@iAction func按钮1(\发送方:任何){
data1.removeAll()
data1.append(contentsOf:getSelectedFileContent(fileName:filename1))
tableView1.reloadData()
}
@iAction func按钮2(\发送方:任何){
data2.removeAll()
data2.append(contentsOf:getSelectedFileContent(fileName:filename2))
tableView2.reloadData()
}
func tableView(tableView:UITableView,