如何在swift的特定部分添加新元素?

时间:2018-04-17 17:01:38

标签: swift uitableview

struct Objects {
    var sectionName: String!
    var sectionObjects: [String]!
}

var objectsArray = [Objects]()

////////////

override func viewDidLoad() {
    super.viewDidLoad()

    setupBluetooth()

    objectsArray = [Objects(sectionName: "Peripherals", sectionObjects: []),
                    Objects(sectionName: "Peripherals Virtual", sectionObjects: [])]
}

////////////////////

extension ViewController: UITableViewDataSource, UITableViewDelegate {

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

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

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

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

        let cell: UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
        let peripheral = peripherals[indexPath.row]

        if peripheral.name == "" || peripheral.name == nil {
            cell.textLabel?.text = String(describing: peripheral.identifier)
        } else {
            cell.textLabel?.text = peripheral.name
        }

        return cell
    }
}

/////// 应用程序本身会搜索应出现在第一部分中的外围设备。但问题是它增加了那里的所有部分,但我只需要第一部分,我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用indexPath.section处理特定部分内的项目

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

    let cell: UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! UITableViewCell

    if indexPath.section == 0 {
        let peripheral = peripherals[indexPath.row]

        if peripheral.name == "" || peripheral.name == nil {
            cell.textLabel?.text = String(describing: peripheral.identifier)
        } else {
            cell.textLabel?.text = peripheral.name
        }

        return cell
    } else {

        // here handle other sections

    }
}
相关问题