上一節實現了一個最簡版的好友列表,但信息實在太單薄。這一節要把好友的頭像、暱稱、在線狀態、個性簽名、網絡狀態等信息都呈現出來。

系統默認的 UITableViewCell 樣式撐不起這麼多元素,所以我們需要自定義。新建一個類,繼承 UITableViewCell。
#import <UIKit/UIKit.h> @interface UserTableViewCell : UITableViewCell @property (strong, nonatomic) UIImageView *headerphoto; // 頭像 @property (strong, nonatomic) UILabel *nameLabel; // 暱稱 @property (strong, nonatomic) UILabel *isOnLine; // 是否在線 @property (strong, nonatomic) UILabel *introductionLabel; // 個性簽名、動態等 @property (strong, nonatomic) UILabel *networkLabel; // 網絡狀態 @end
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
headerphoto = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 50, 50)];
[self.contentView addSubview:headerphoto];
nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 200, 25)];
nameLabel.backgroundColor = [UIColor clearColor];
nameLabel.font = [UIFont systemFontOfSize:16];
[self.contentView addSubview:nameLabel];
isOnLine = [[UILabel alloc] initWithFrame:CGRectMake(60, 40, 50, 5)];
isOnLine.font = [UIFont systemFontOfSize:10];
[self.contentView addSubview:isOnLine];
introductionLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 40, 180, 5)];
introductionLabel.font = [UIFont systemFontOfSize:10];
[self.contentView addSubview:introductionLabel];
networkLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 5, 50, 25)];
networkLabel.font = [UIFont systemFontOfSize:10];
[self.contentView addSubview:networkLabel];
}
return self;
}
所有子視圖都掛在 contentView 上,而不是直接加在 cell 本身,這是自定義 cell 的慣例做法。
回到 view controller,修改 table view 的數據源方法:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = [titleArray objectAtIndex:indexPath.section];
NSArray *arr = [dataDic objectForKey:str];
static NSString *CellIdentifier = @"UserCell";
UserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil) {
cell = [[UserTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
NSDictionary *dic = [arr objectAtIndex:indexPath.row];
cell.headerphoto.image = [UIImage imageNamed:[dic valueForKey:@"usericon"]];
cell.nameLabel.text = [dic valueForKey:@"name"];
cell.isOnLine.text = @"[在線]";
cell.introductionLabel.text = @"無動態";
cell.networkLabel.text = @"4G";
return cell;
}
把 cell 換成自定義的 UserTableViewCell,之後就能完全按自己的設計稿去實現樣式了。
順帶一提,上面 dequeueReusableCellWithIdentifier: 之後緊跟一句 cell = nil,實際效果是讓緩存複用徹底失效,每次滾動都要新建 cell。學習階段這樣寫沒問題,但正式專案裡應該去掉這行,把 cell 的屬性賦值寫在 if (cell == nil) 之外,才能享受到複用帶來的流暢度。
至此,好友信息的基礎展示就完成了。下一節我們來把分組折疊功能加上。