繁体   English   中英

如何在swift中的tableview中的不同多个部分中添加多行

[英]How to add multiple rows in different multiple sections in tableview in swift

我在该单元格中有tableview我已经在该标题中创建了标题视图我有标签和按钮,我从数组中获取标签值,该数组计算可正常工作的节数。 但是当我点击按钮时我需要扩展单元格,在那个扩展的单元格中我需要添加标签,但是当我点击按钮时它说

错误:索引超出范围

numberOfRowsInSection ,它没有展开。

这是我的代码:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DataSendingDelegateProtocol, FieldsDelegateProtocol {
var shouldCellBeExpanded:Bool = false
var indexOfExpendedCell:NSInteger = -1
// let kHeaderSectionTag: Int = 6900;

@IBOutlet weak var tableView: UITableView!
var sectionArray = [String]()
var sectionItemsArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    //self.tableView!.tableFooterView = UIView()
}

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)
}

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

func sendDataToTableRow(myData: String) {
    self.sectionItemsArray.append(myData)
    tableView.reloadData()
   // print(iteamsArray)
}

func sendDataToSectionLabel(myData: String) {
    self.sectionArray.append(myData)
    tableView.reloadData()
    print(sectionArray)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "segue") {
        let vc = segue.destination as! PopViewController
        vc.delegate = self
    }
    else if (segue.identifier == "fieldsSegue") {
        let vc = segue.destination as! FieldsViewController
        vc.delegate = self
    }
}
@objc func expandButnClicked(sender:UIButton){

    print("expand button tapped")

    shouldCellBeExpanded = !shouldCellBeExpanded
    indexOfExpendedCell = sender.tag

    if shouldCellBeExpanded {

        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    }
    else {
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    }
}

@IBAction func addBtn(_ sender: Any) {
}

// MARK: - Tableview Methods
func numberOfSections(in tableView: UITableView) -> Int {

    return sectionArray.count
}

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

    if (self.indexOfExpendedCell == section) {
        let arrayOfItems = self.sectionItemsArray[section]
        return arrayOfItems.count
    } else {
        return 0
    }
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if (self.sectionArray.count != 0) {
        return self.sectionArray[section] as? String
    }
    return ""
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44.0;
}

/*func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
    return 0;
}*/

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

    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.contentView.backgroundColor = UIColor.colorWithHexString(hexStr: "#0075d4")
    header.textLabel?.textColor = UIColor.white

    let button = UIButton(frame: CGRect(x: 380, y: 10, width: 15, height: 15))
    button.backgroundColor = UIColor.green
    button.tag = section
    button.addTarget(self, action: #selector(expandButnClicked), for: .touchUpInside)

    header.addSubview(button)
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    if shouldCellBeExpanded && indexPath.row == indexOfExpendedCell {
        return 200
    }
    else {
        return 0
    }
}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! TableViewCell

    cell.textLab?.textColor = UIColor.black
    cell.textLab.text = sectionItemsArray[indexPath.row]
    cell.backgroundColor = UIColor.black
    return cell
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}
}

请帮我修改代码。

如果section被展开,则返回sectionOtemsArray数组countOfRowsInSection方法中的count

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (self.indexOfExpendedCell == section) {
        return self.sectionItemsArray.count
    } else {
        return 0
    }
}

您的问题可以精确定位到您实施的两种方法:

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

    return sectionArray.count
}

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

    if (self.indexOfExpendedCell == section) {
        let arrayOfItems = self.sectionItemsArray[section]
        return arrayOfItems.count
    } else {
        return 0
    }
}

在第一个中,您解释了您使用sectionArray但是在第二部分中您使用了另一个数组sectionItemsArray sectionItemsArray[sectionArray.count-1]情况下很可能发生崩溃,当sectionItemsArray的元素数量少于sectionArray时,它将失败。

您可能应该具有此一致性并且仅使用一个数组。 在您的情况下,使用数组数组来表示节和行是有意义的。 但总的来说,使用自定义结构可能更好。 考虑以下内容:

class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    class Section {
        class Row {
            let name: String
            var shown: Bool = true
            init(name: String) { self.name = name }
        }
        let name: String
        var shown: Bool = true
        var rows: [Row]

        init(name: String, rows: [Row] = [Row]()) { self.name = name; self.rows = rows }
    }

    var sections: [Section]!

    override func viewDidLoad() {
        super.viewDidLoad()
        sections = [
            Section(name: "Empty"),
            Section(name: "Second section", rows: [.init(name: "row 1"), .init(name: "row 2")]),
            Section(name: "Third section", rows: [.init(name: "row 1"), .init(name: "row 2")])
        ]
    }


    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.filter { $0.shown }.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections.filter { $0.shown }[section].name
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections.filter { $0.shown }[section].rows.filter { $0.shown }.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let name: String = sections.filter { $0.shown }[indexPath.section].rows.filter { $0.shown }[indexPath.row].name
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = name
        return cell
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM