How to reload a UITableView after a segmented control changed?

十年热恋 提交于 2019-12-11 14:28:51

问题


I am trying to control context of tableview with segmented control(which is above tableview). On change segment I want to reload data in my table tableView with different cells ( I have two types of cells and two data arrays for every type). How to clear and reload data with different cell ?


回答1:


I'm just providing a few lines of code to what @jaydee3 has mentioned.

- (IBAction)segmentControlValueChanged:(UISegmentedControl *)sender
{
    //Do something
    [self.tableView reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.segmentControl.selectedSegmentIndex?[self.dataArray2 count]:[self.dataArray1 count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.segmentControl.selectedSegmentIndex){
       // Create Type cell for selected Index 1
    }
    else{
       // Create Type cell for selected Index 0
    }
}



回答2:


In your tableView delegate, check what is selected in the segmented control and return the correct cells.

If the segmented control gets changed, call reloadData on the tableView.




回答3:


1.Below is most important line if you want to change the data in 2 or more tableview.

@IBAction func segmentValueChanged(_ sender: UISegmentedControl) 
{
    self.<YourTableViewName>.reloadData()
}

2.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var index = <segmentObjectCreated>.selectedSegmentIndex

    if index == 0 {
        return <table1ArrayList>.count
    }
    else{
        return <table12ArrayList>.count
    }
}

3.

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

    var index = <segmentObjectCreated>.selectedSegmentIndex

    if index == 0 {
        cell.textLabel?.text = <table1ArrayList>[indexPath.row].productName
    }
    else {
        cell.textLabel?.text = <table2ArrayList>[indexPath.row].newLaunch
    }
    return cell
}

That's it, Happy Coding!



来源:https://stackoverflow.com/questions/15350333/how-to-reload-a-uitableview-after-a-segmented-control-changed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!