如何使用 swift 用两个不同的数组填充表视图中的两个部分?

How do I populate two sections in a tableview with two different arrays using swift?

我有两个数组 Data1 和 Data2,我想将每个数组中的数据(它们包含字符串)填充到两个不同部分的表视图中。

第一部分的标题应为 "Some Data 1",第二部分的标题应为 "KickAss"。

我用第一个数组中的数据填充了两个部分(但也没有标题)。

到目前为止,这是我的代码:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var rowCount = 0
    if section == 0 {
        rowCount = Data1.count
    }
    if section == 1 {
        rowCount = Data2.count
    }
    return rowCount
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    let ip = indexPath
    cell.textLabel?.text = Data1[ip.row] as String
    return cell
}

在 cellForRowAtIndexPath 方法中,我是否可以像在 numberOfRowsInSection 方法中那样以某种方式识别该部分?

另外,如何给每个部分命名?

您可以通过查看 indexPath.section 来确定您所在的部分。 要指定标题,请覆盖函数

func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String!

TableView 单元格

您可以使用多维数组。例如:

let data = [["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"]]

节数使用:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return data.count
}

然后,要指定每个部分中的行数,请使用:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data[section].count
}

最后,您需要设置您的单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellText = data[indexPath.section][indexPath.row]

    //  Now do whatever you were going to do with the title.
}

表格视图Headers

您可以再次使用数组,但这次只有一维:

let headerTitles = ["Some Data 1", "KickAss"]

现在设置章节的标题:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section < headerTitles.count {
        return headerTitles[section]
    }

    return nil
}

上面的代码检查该部分是否有标题,然后 returns 它,否则返回 nil。如果 headerTitles 中的标题数小于 data 中的数组数,则不会有标题。

结果

您可以创建一个 Struct 来保存属于某个部分的数据,以替代我之前的回答。例如:

struct SectionData {
    let title: String
    let data : [String]

    var numberOfItems: Int {
        return data.count
    }

    subscript(index: Int) -> String {
        return data[index]
    }
}

extension SectionData {
    //  Putting a new init method here means we can
    //  keep the original, memberwise initaliser.
    init(title: String, data: String...) {
        self.title = title
        self.data  = data
    }
}

现在在您的视图控制器中,您可以像这样设置您的部分数据:

lazy var mySections: [SectionData] = {
    let section1 = SectionData(title: "Some Data 1", data: "0, 1", "0, 2", "0, 3")
    let section2 = SectionData(title: "KickAss", data: "1, 0", "1, 1", "1, 2")

    return [section1, section2]
}()

小节Headers

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return mySections.count
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return mySections[section].title
}

与我之前的回答相比,您现在不必担心将 headerTitles 的数量与 data 中的数组数量进行匹配。

TableView 单元格

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return mySections[section].numberOfItems
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellTitle = mySections[indexPath.section][indexPath.row]

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = cellTitle

    return cell
}

在Swift4或Swift5中您可以使用下面的代码。

此处显示了带有过滤器的自定义 header 部分:

  1. 创建项目
  2. 添加table视图
  3. 创建 UITableView 单元格
  4. 将标签连接到 uitable 视图 & table 使用视图控制器
  5. 添加以下代码

    import UIKit
    
    struct Category {
    let name : String
    var items : [[String:Any]]
    }
    
     class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {
      @IBOutlet weak var txtName: UITextField!
    
     @IBOutlet weak var tableView: UITableView!
    
    var originalArr = [[String:Any]]();
    var recentArr = [[String:Any]]();
    var searchArrRes = [[String:Any]]()
    var searching:Bool = false
    
     //
    var sections = [Category]()
    
    override func viewDidLoad() {
      super.viewDidLoad()
    
    //Assign delegate  don't forget
    txtName.delegate = self
    tableView.delegate = self
    tableView.dataSource = self
    
    
    
    recentArr =   [
        ["name": "Enamul", "number": "+8800000003"],
        ["name": "Enam", "number": "+8800000004"]
    ]
    
    originalArr = [
        ["name": "abdul", "number": "+8800000001"],
        ["name": "abdin", "number": "+8800000002"],
        ["name": "Enamul", "number": "+8800000003"],
        ["name": "enam", "number": "+8800000004"],
        ["name": "Rafi", "number": "+8800000005"],
        ["name": "Ehaque", "number": "+8800000006"]
       ]
    
     //my array
      sections = [
          Category(name:"Recent", items:recentArr),
          Category(name:"ALL", items:originalArr)
          ]
    
          }
    
    
       func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
         }
    
     func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
          guard let tableView = view as? UITableViewHeaderFooterView else { return }
    
       tableView.textLabel?.textColor = UIColor.red
     }
    
     public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
    //input text
    let searchText  = textField.text! + string
    
    searchArrRes = self.originalArr.filter({(([=10=]["name"] as! String).localizedCaseInsensitiveContains(searchText))})
    
    
    if(searchArrRes.count == 0){
        searching = false
    }else{
        searching = true
    }
    self.tableView.reloadData();
    
    return true
    }
    
    
      func numberOfSections(in tableView: UITableView) -> Int {
    if( searching == true){
        return 1
        }
       return self.sections.count
       }
    
      func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if( searching == true){
        return ""
       }
      return self.sections[section].name
      }
    
       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if( searching == true){
       return searchArrRes.count
    }else{
        let items = self.sections[section].items
        return items.count
      }
     }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custom_cell
      //  var dict = itemsA[indexPath.section]
    
    if( searching == true){
        var dict = searchArrRes[indexPath.row]
        cell.name.text = dict["name"] as? String
        cell.number.text = dict["number"] as? String
     }else{
        let items = self.sections[indexPath.section].items
        let item = items[indexPath.row]
        cell.name.text = item["name"] as? String
        cell.number.text = item["number"] as? String
    
        }
    
        return cell
         }
    
    
    }
    

您可以从 GitHub.GitHub 下载完整源代码,例如:https://github.com/enamul95/Custom_table_view_section.git

可以在 Tableview 中创建 Sections 并且可以更改 Header sections 的颜色

   class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tabview: UITableView!

var tablecell = NewTableViewCell()

let data = [["SWIFT", "BALENO", "ALTO", "CIAZ"], ["INNOVA", "GLANZA", "FORTUNER"] , ["BMW X5", "BMW M4", "BMW 7 Series", "BMW X7", "BMW i3"]]

let brand: Array<String> = ["MARUTHI", "TOYOTA", "BMW"]



override func viewDidLoad() {
    super.viewDidLoad()

}


 func numberOfSections(in tableView: UITableView) -> Int {
    return brand.count
}

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


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    return self.brand[section]

}


func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    // can change the header color of background and title with this code :)

    (view as! UITableViewHeaderFooterView).contentView.backgroundColor = UIColor.red.withAlphaComponent(0.4)
    (view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.yellow

    }



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

    let cell1: NewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! NewTableViewCell

    let text = data[indexPath.section][indexPath.row]

    cell1.textLabel!.text = text

    return cell1
}




override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}