在我们不想用系统封装好的cell时,就可以自定义了
自定义多个Cell
1.自定义多个Cell时,会用到
/**tableView有多少组*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 4; // 4代表给表视图返回4个组
}
2.在自定义多个Cell的时候,一定要使用不同的标示符,比如:
static NSString *activityCellID = @“activityCell";
NSString *mapCellID = @“mapID";
NSString *mustCellID = @“mustID";
NSString *chatCellID = @“chatID";
自定义了四个Cell,就用四个不同的标示符
3.在自定义多个Cell,实现
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
方法时:
// 如果返回值是nil,就必须保证有一个可用的cell返回,如果没有就会崩溃。
return nil;
4.在第一个Cell上有两个按钮,我们在点击的时候,要想知道我们点击了哪一个按钮和哪一个cell,就得通过 代理 传值 。下面是具体做法:
#import <UIKit/UIKit.h>
1⃣️:@class Detail_TableViewCell;//要用它就得先导入类名
@protocol Detail_TableViewCellDelegate <NSObject> // 声明代理
@required
- (void) didClickButton:(UIButton *)button tableCell:(Detail_TableViewCell *)cell; // 声明代理方法
@end
@interface Detail_TableViewCell : UITableViewCell
@property (nonatomic,assign) id<Detail_TableViewCellDelegate> delegate; // 标明代理属性
@end
2⃣️:- (void) clickAiction:(UIButton *)sender{
/*要想知道点击的是哪一个cell上的按钮,把cell和点击的按钮传过去*/
/*点击按钮的时候触发这个方法*/
[self.delegate didClickButton:sender tableCell:self];
}
3⃣️:在创建tableView的页面导入代理:
@interface Activity_ViewController ()<UITableViewDataSource,UITableViewDelegate,Detail_TableViewCellDelegate>
4⃣️:在初始化该cell的地方,挂上代理:
cell.delegate = self;
5⃣️:实现代理方法
- (void) didClickButton:(UIButton *)button tableCell:(Detail_TableViewCell *)cell{
/**indexPathForCell 通过cell查找到 cell所在的组 和行*/
NSIndexPath *indexPath = [activityView indexPathForCell:cell];
NSLog(@"点击的是%ld组,%ld行,%ld按钮",indexPath.section,indexPath.row,button.tag);
}
这样,就可以把点击的按钮和cell的位置告诉系统了
5.最后一个cell,是聊天的cell,在
上添加手势,改变聊天栏的行数:
- (void) touchTo:(UITapGestureRecognizer *) sender{
rowNumbers = rowNumbers!=1 ? 1:30;
[activityView reloadData]; // 更新表视图的内容数据
if (rowNumbers == 1) {
[UIView animateWithDuration:0.5 animations:^{
activityView.contentOffset = CGPointMake(0, 200);
}];
}
}
6.要在表头上自定义视图,就需要在表头上添加一层 UIView作为父视图,不然我们无法设置它的frame,这是要点!