How to reload a UITableView after a segmented cont

2019-08-12 18:18发布

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 ?

标签: ios ios6
3条回答
Deceive 欺骗
2楼-- · 2019-08-12 18:27

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!

查看更多
虎瘦雄心在
3楼-- · 2019-08-12 18:28

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.

查看更多
走好不送
4楼-- · 2019-08-12 18:39

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
    }
}
查看更多
登录 后发表回答