表格视图与部分使用单个数组

时间:2017-02-16 03:46:03

标签: swift

我有一张桌子,上面有这些项目的一些项目和部分。这些项目和部分都是硬编码的,我在理解如何从一个数组而不是两个数组加载所有内容时遇到一些麻烦。

这是我的代码:

 import UIKit

class Beta: UIViewController, UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak var tableView: UITableView!


    let section = ["Fruits", "Vegetables"]
    let items = [["Apple", "Banana"], ["Carrots", "Broccoli"]]






    override func viewDidLoad(){
        super.viewDidLoad()
        self.tableView.allowsMultipleSelection = true




    }

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




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

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


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


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

        cell.textLabel?.text = self.items[indexPath.section][indexPath.row]

        //MARK: -Checkmark and save support.
        cell.accessoryType = cell.isSelected ? .checkmark : .none
        cell.selectionStyle = .none // to prevent cells from being "highlighted"



        return cell
    }









}





}

我使用了我可以在网上找到的代码,我能找到的唯一可用代码的部分和项目分成两个数组。

如何让它读取这一个数组的所有内容?

var Food:NSDictionary = [
        //:Section Title : Items
        "Fruits" : ["Apple","Banana"],
        "Vegetables" : ["Carrots","Broccoli"]
    ]

2 个答案:

答案 0 :(得分:1)

试试这个 -

struct Section {
 var name: String!
 var items: [String]!
 init(name: String, items: [String]) {
    self.name = name
    self.items = items
 }
}


import UIKit

class Beta: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tblView: UITableView!
var sections = [Section]()
override func viewDidLoad() {
    super.viewDidLoad()
    self.tblView.estimatedRowHeight = 56.0
    self.tblView.rowHeight = UITableViewAutomaticDimension
    self.tblView.tableFooterView = UIView()
     // Initialize the sections array
    sections = [
        Section(name: "Fruits", items: ["Apple", "Banana"]),
        Section(name: "Vegetables", items: ["Carrots", "Broccoli"]),
    ]
 }

 func numberOfSections(in tableView: UITableView) -> Int {
    return 1
 }

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

    // For section 1, the total count is items count plus the number of headers
    var count = sections.count

    for section in sections {
        count += section.items.count
    }

    return count
   }

 // Add two prototype cell in your storyboard and give identifier "header" for header cell and "cell" for another one. 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: UITableViewCell?
    // Calculate the real section index and row index
    let section = getSectionIndex(row: indexPath.row)
    let row = getRowIndex(row: indexPath.row)

        if row == 0 {
        let headerCell = tableView.dequeueReusableCell(withIdentifier: "header")! as UITableViewCell
        headerCell.textLabel?.numberOfLines = 0
        headerCell.textLabel?.textColor = UIColor.blue
        headerCell.textLabel?.lineBreakMode = .byWordWrapping
        headerCell.textLabel?.text = sections[section].name
        headerCell.selectionStyle = .none
        return headerCell
    } else {
            if cell == nil {
                cell = tableView.dequeueReusableCell(withIdentifier: "cell")
            }
        cell?.textLabel?.numberOfLines = 0
        cell?.textLabel?.lineBreakMode = .byWordWrapping
        cell?.selectionStyle = .none
        cell?.textLabel?.text = sections[section].items[row - 1]
        }
        return cell!
    }

//
// MARK: - Helper Functions
//
func getSectionIndex(row: NSInteger) -> Int {
    let indices = getHeaderIndices()

    for i in 0..<indices.count {
        if i == indices.count - 1 || row < indices[i + 1] {
            return i
        }
    }

    return -1
}

func getRowIndex(row: NSInteger) -> Int {
    var index = row
    let indices = getHeaderIndices()

    for i in 0..<indices.count {
        if i == indices.count - 1 || row < indices[i + 1] {
            index -= indices[i]
            break
        }
    }

    return index
}

func getHeaderIndices() -> [Int] {
    var index = 0
    var indices: [Int] = []

    for section in self.sections {
        indices.append(index)
        index += section.items.count + 1
    }

    return indices
   }


  }

答案 1 :(得分:0)

你很接近,但你错误地使用了没有订单的字典。你需要一个数组。它可以是一个单项词典,甚至是元组的数组:

let arr : [(String, [String])] = ...

更好的是,创建一个自定义结构并使用它的数组:

struct Model {
    let section : String
    let rows : [String]
}

现在您的数据是[Model]