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!