user579911 user579911 - 4 months ago 9
iOS Question

update number of rows in section for segment control selection

Am new to swift programming. I have a tableview with single custom cell.On top of the page i have a segment control. In my custom cell i have two labels and textfields. When the page is loaded, first segment will be in selected state in segment control and table rows count should be 5.

If am selecting the 2nd option in segment, I should load one more row i.e. 6th row and hide one textfield from second row. Am able to load the tableview with 5 rows. And when user selects from segment am not able to reload the table with 6 rows. Here is my code,

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

let numberOfRowsAtSection: [Int] = [5, 6]
var selectedOption: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
reportTable.delegate = self
reportTable.dataSource = self
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows: Int = 0
if tableView == self.reportTable && selectFromOptions.selectedSegmentIndex == 0 && selectedOption == true {
selectedOption = false;
if section == 0 {
rows = 5
}
} else if selectFromOptions.selectedSegmentIndex == 1 && selectedOption == true {
if section == 1 {
rows = 6
}
}
return rows
}

@IBAction func optionChanges(sender: UISegmentedControl) {
switch selectFromOptions.selectedSegmentIndex {
case 0:
selectedOption = true
reportTable.reloadData()
case 1:
selectedOption = true
reportTable.reloadData()

default:
break;
}
}


How can i achieve the above? Thanks in advance.

Answer

You have a mistake in your code where you check the section if section == 1. There is only ever one section and its index is always 0. You should be able to discover this by setting a breakpoint in selectedOption and stepping through to see what values are being passed in and what code path you go down.

I think this should work:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var rows: Int = 0
    if tableView == self.reportTable && selectFromOptions.selectedSegmentIndex == 0 && selectedOption == true {
        selectedOption = false;
        if section == 0 {
            rows = 5
        }
    } else if selectFromOptions.selectedSegmentIndex == 1 && selectedOption == true {
        if section == 0 {
            rows = 6
        }
    }
    return rows
}

I don't have the full context of your code, but it seems like there may be some needless conditions in the above. Does this not produce the desired result?

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch selectFromOptions.selectedSegmentIndex {
    case 0:
        return 5
    case 1:
        return 6
    default:
        return 0
    }
}