user9328598
user9328598

Reputation:

How to add a new element in specific section swift?

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
    }
}

/////// The application itself searches for the peripherals that should appear in the first section. But the problem is that it adds to all the sections that are there, but I need only the first, how do I do this?

Upvotes: 1

Views: 626

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Use indexPath.section to handle items inside a specific 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

    }
}

Upvotes: 1

Related Questions