动态TableView
在ViewController中添加一个Table View上去,选择Dynamic Prototypes,如下:

除了必须实现dataSource里面的三个方法以外,还可以自定义首尾标识符:
//header
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView * header = [[UIView alloc] init];
if ( section == 0 ) {
header.backgroundColor = [UIColor lightGrayColor];
} else {
header.backgroundColor = [UIColor darkGrayColor];
}
return header;
}
//footer
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIView * footer = [[UIView alloc] init];
if ( section == 0 ) {
footer.backgroundColor = [UIColor blueColor];
} else {
footer.backgroundColor = [UIColor cyanColor];
}
return footer;
}
静态TableView
在ViewController中添加一个Table View上去,选择Static Prototypes,如下:

静态方法不用实现dataSource中的三个方法,因为在tableView的UI上已经做好了,该方法适合不用更新的tableView:


但是可以实现delegate方法,点击该Cell时,会跳转到其他界面:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ( indexPath.section == 0 && indexPath.row == 1 ) {
[self performSegueWithIdentifier:@"showWiFi" sender:self];
} else {
// TODO : handle it!
}
}
Wife的界面中向下拉tableView会出现如菊花状的图形,代码如下:
- (IBAction)startRefresh:(id)sender {
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"scanning"];
}
- (void) stopRefreshing {
[self.refreshControl endRefreshing];
[self.tableView reloadData];
}
把Xib当Cell加载进TableView
设计一个Xib如下:

在XibCell.m文件中定义初始化函数:
- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
// The Xib will not be loaded automatically in super's -initWithStyle:reuseIdentifier:
NSArray * uiObjects = [[NSBundle mainBundle] loadNibNamed:@"XibCell" owner:self options:nil];
self = uiObjects[0]; // don't do this in real project, it is only for demonstration, register the xib instead.
return self;
}
在ViewController中加载该Xib:
UINib * nib = [UINib nibWithNibName:@"XibCell" bundle:nil]; // nil means [UIBundle mainBundle]
[self.tableView registerNib:nib forCellReuseIdentifier:CELL_ID];
self.tableView.rowHeight = 120.0f;
[self.tableView registerClass:[XibCell class] forCellReuseIdentifier:CELL_ID];
若需要在ViewConrtoller中调用Xib中的按钮响应,需要添加代理:
@protocol btnClickedDelegate <NSObject>
-(void)cellBtnClicked;
@end
@interface MyXibTableViewCell : UITableViewCell
@property (nonatomic,weak) id<btnClickedDelegate> btnDelegate;
排序与索引
要对tableview中的cell排序方法如下:
[Array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];
}];
得到该数组的首字母,并分好有几个section,对其首字母分类:
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return [_secIndex count];
}
并设置header的title:
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return [_secIndex count];
}
这样就可以做好分类了,接下来一个函数就可以实现索引:
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return [_secIndex count];
}
网友评论