我已经为您的要求创建了代码,请找到下面的 url 下载代码并查看它。
链接:https://www.dropbox.com/s/22ijwgxybn98wyj/ExpandCollapse.zip?dl=0
环境:Xcode 8 和 Objective-C
突出显示我编写的代码。
我已经根据你的结构创建了student的NSObject,创建了两个(StudentListCell和ShowMoreCell)UITableViewCell用于显示student的记录和“Show Remaining button”记录。
我还拿了两个(arrStudentInfo, arrSearchInfo) NSMutablebleArray 来保存搜索记录和原始记录。
之后我在ViewController.m 中初始化student 的NSObject。请找到以下代码。
- (void)setupData {
self.arrStudentInfo = [[NSMutableArray alloc] init];
self.arrSearchInfo = [[NSMutableArray alloc] init];
StudentInfo *student_1 = [[StudentInfo alloc] init];
student_1.name = @"Sia S";
student_1.style = @"S";
student_1.trend = @"S";
student_1.age = @"60";
student_1.locale = @"Node";
student_1.street = @"BR";
student_1.city = @"JP";
student_1.country = @"US";
student_1.isOpen = YES;
student_1.isShowMore = NO;
[self.arrStudentInfo addObject:student_1];
StudentInfo *student_2 = [[StudentInfo alloc] init];
student_2.name = @"Nitin";
student_2.style = @"N";
student_2.trend = @"N";
student_2.age = @"40";
student_2.locale = @"Node";
student_2.street = @"BR";
student_2.city = @"SP";
student_2.country = @"US";
student_2.isOpen = YES;
student_2.isShowMore = NO;
[self.arrStudentInfo addObject:student_2];
}
我已经创建了返回当前活动的方法,这意味着搜索记录或数组的原始记录。
- (NSMutableArray *)getCurrentArray {
if(self.isSearch)
return self.arrSearchInfo;
else
return self.arrStudentInfo;
}
根据场景加载数据,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
StudentInfo *studentInfo = [self getCurrentArray][indexPath.section];
if(indexPath.row == SHOW_MORE_INDEX && studentInfo.isShowMore == NO) {
static NSString *strCellIdentifier = @"ShowMoreCell";
ShowMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:strCellIdentifier];
cell.btnShowMore.tag = indexPath.section;
[cell.btnShowMore addTarget:self action:@selector(clickONShowMore:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
else {
static NSString *strCellIdentifier = @"StudentListCell";
StudentListCell *cell = [tableView dequeueReusableCellWithIdentifier:strCellIdentifier];
[cell setupCell:studentInfo indexPath:indexPath];
return cell;
}
}
用于搜索学生姓名,
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
self.isSearch = YES;
NSPredicate *predicateStudent = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"self.name CONTAINS[cd] '%@'",searchBar.text]];
NSArray *arrGetSearch = [self.arrStudentInfo filteredArrayUsingPredicate:predicateStudent];
if(self.arrSearchInfo.count)
[self.arrSearchInfo removeAllObjects];
[self.arrSearchInfo addObjectsFromArray:arrGetSearch];
[self.tblView reloadData];
}
如果用户单击UISearchbar 上的“X”按钮,则再次加载原始记录。
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if([searchText isEqualToString:@""] || searchText==nil) {
[searchBar resignFirstResponder];
self.isSearch = NO;
[self.tblView reloadData];
}
}
希望这对你有用。