您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

用 UITableView 打造 QQ 風格好友列表:從基本列表到可折疊分組

編輯:iOS 開發綜合

基本實現

一、專案結構與 plist 資料

二、實作程式碼

主控制器直接繼承 UITableViewController,並在 storyboard 中完成關聯。

資料模型部分:好友列表是兩層結構,外層是「分組」,內層是「好友」,因此設計兩個模型。

// YYQQGroupModel.h
#import <Foundation/Foundation.h>

@interface YYQQGroupModel : NSObject
@property (nonatomic, copy) NSString *name;      // 分組名稱
@property (nonatomic, copy) NSString *online;    // 在線人數
@property (nonatomic, strong) NSArray *friends;  // 好友列表
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)qqGroupModelWithDict:(NSDictionary *)dict;
@end

// YYQQGroupModel.m
@implementation YYQQGroupModel
- (instancetype)initWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
        // 把 friends 陣列中的字典逐一轉成模型
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:self.friends.count];
        for (NSDictionary *dict in self.friends) {
            [models addObject:[YYFriendsModel friendsWithDict:dict]];
        }
        _friends = [models copy];
    }
    return self;
}
+ (instancetype)qqGroupModelWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}
@end

// YYFriendsModel.h
@interface YYFriendsModel : NSObject
@property (nonatomic, copy) NSString *name;   // 暱稱
@property (nonatomic, copy) NSString *icon;   // 頭像
@property (nonatomic, copy) NSString *intro;  // 個性簽名
@property (nonatomic, assign, getter = isVip) BOOL vip;
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)friendsWithDict:(NSDictionary *)dict;
@end

視圖部分:自訂一個 cell,把模型資料灌進系統內建的 Subtitle 樣式。

// YYfriendCell.m
+ (YYfriendCell *)cellWithTableview:(UITableView *)tableView
{
    static NSString *identifier = @"qq";
    YYfriendCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[YYfriendCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                   reuseIdentifier:identifier];
    }
    return cell;
}

- (void)setFriends:(YYFriendsModel *)friends
{
    _friends = friends;
    self.imageView.image = [UIImage imageNamed:_friends.icon];
    self.textLabel.text = _friends.name;
    self.detailTextLabel.text = _friends.intro;

    // 會員名子顯示紅色,其餘顯示黑色
    // 注意:這裡一定要寫 else 分支,否則 cell 重用時顏色會殘留
    if (_friends.isVip) {
        [self.textLabel setTextColor:[UIColor redColor]];
    } else {
        [self.textLabel setTextColor:[UIColor blackColor]];
    }
}

主控制器部分:用懶載入讀取 plist 並轉模型,再實作 UITableView 的資料來源方法。

// YYViewController.m
- (NSArray *)groupFriends
{
    if (_groupFriends == nil) {
        NSString *fullpath = [[NSBundle mainBundle] pathForResource:@"friends.plist"
                                                            ofType:nil];
        NSArray *arrayM = [NSArray arrayWithContentsOfFile:fullpath];
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:arrayM.count];
        for (NSDictionary *dict in arrayM) {
            [models addObject:[YYQQGroupModel qqGroupModelWithDict:dict]];
        }
        _groupFriends = [models copy];
    }
    return _groupFriends;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.sectionHeaderHeight = 100;
}

#pragma mark - 資料來源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.groupFriends.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    YYQQGroupModel *group = self.groupFriends[section];
    return group.friends.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YYfriendCell *cell = [YYfriendCell cellWithTableview:tableView];
    YYQQGroupModel *group = self.groupFriends[indexPath.section];
    cell.friends = group.friends[indexPath.row];
    return cell;
}

#pragma mark - 代理方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor grayColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

- (BOOL)prefersStatusBarHidden { return YES; }

這是最樸素的版本:

三、注意點

(1)分組頭部視圖透過 viewForHeaderInSection: 與 heightForHeaderInSection: 兩個方法搭配設定。

(2)重寫 setter 時一定要考慮「復原」的情況,也就是 vip 與非 vip 都要明確指定顏色,否則重用 cell 會出現顏色錯亂。

更進階的實現:可折疊分組

一、效果

二、關鍵改動

模型層只需要多一個開合狀態:

// YYQQGroupModel.h
@property (nonatomic, assign, getter = isOpen) BOOL open;   // 該組目前是否展開

cell 部分加上字型調整:

self.textLabel.font = [UIFont systemFontOfSize:15.f];
self.detailTextLabel.font = [UIFont systemFontOfSize:10.f];

重點是自訂的分組頭部 YYHeaderView,它繼承自 UITableViewHeaderFooterView,內部放一個 button(背景圖+箭頭)與一個顯示在線人數的 label,並透過 delegate 把「點擊」事件交回控制器。

// YYHeaderView.h
@class YYQQGroupModel, YYHeaderView;

@protocol YYHeaderViewDelegate <NSObject>
- (void)headerViewDidClickHeaderView:(YYHeaderView *)headerView;
@end

@interface YYHeaderView : UITableViewHeaderFooterView
@property (nonatomic, strong) YYQQGroupModel *group;
+ (instancetype)headerWithTableView:(UITableView *)tableView;
@property (nonatomic, weak) id<YYHeaderViewDelegate> delegate;
@end

// YYHeaderView.m
+ (instancetype)headerWithTableView:(UITableView *)tableView
{
    static NSString *indentifier = @"header";
    YYHeaderView *headerview = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (headerview == nil) {
        headerview = [[YYHeaderView alloc] initWithReuseIdentifier:indentifier];
    }
    return headerview;
}

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    // 注意:建構子中設定的 frame 是無效的,必須在 layoutSubviews 裡處理
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:@"buddy_header_bg"]
                       forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"buddy_header_bg_highlighted"]
                       forState:UIControlStateHighlighted];
        [btn setImage:[UIImage imageNamed:@"buddy_header_arrow"]
             forState:UIControlStateNormal];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnOnclick:)
      forControlEvents:UIControlEventTouchUpInside];
        // 讓箭頭圖片以原尺寸置中顯示,且不被裁切
        btn.imageView.contentMode = UIViewContentModeCenter;
        btn.imageView.layer.masksToBounds = NO;
        [self addSubview:btn];
        self.btn = btn;

        UILabel *lab = [[UILabel alloc] init];
        lab.textAlignment = NSTextAlignmentRight;
        lab.textColor = [UIColor grayColor];
        [self addSubview:lab];
        self.lab = lab;
    }
    return self;
}

- (void)btnOnclick:(UIButton *)btn
{
    self.group.open = !self.group.isOpen;   // 1. 更新模型
    // 2. 通知代理刷新表格
    if ([self.delegate respondsToSelector:@selector(headerViewDidClickHeaderView:)]) {
        [self.delegate headerViewDidClickHeaderView:self];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];   // 一定要記得呼叫父類
    self.btn.frame = self.bounds;

    CGFloat padding = 20, labW = 50;
    self.lab.frame = CGRectMake(self.frame.size.width - padding - labW, 0,
                                labW, self.frame.size.height);
}

// 已加入父視圖時呼叫,此時才拿得到最新的 frame,適合調整箭頭方向
- (void)didMoveToSuperview
{
    if (self.group.isOpen) {
        self.btn.imageView.transform = CGAffineTransformMakeRotation(M_PI_2);
    }
}

- (void)setGroup:(YYQQGroupModel *)group
{
    _group = group;
    // 設定按鈕文字時必須指定 state,直接改 titleLabel.text 不會顯示
    [self.btn setTitle:_group.name forState:UIControlStateNormal];
    self.lab.text = [NSString stringWithFormat:@"%@/%d", _group.online, _group.friends.count];
}
@end

控制器端則用 numberOfRowsInSection: 決定折疊行為,並實作代理回呼。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    YYQQGroupModel *group = self.groupFriends[section];
    return group.isOpen ? group.friends.count : 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YYHeaderView *headerview = [YYHeaderView headerWithTableView:tableView];
    headerview.delegate = self;
    headerview.group = self.groupFriends[section];
    return headerview;
}

- (void)headerViewDidClickHeaderView:(YYHeaderView *)headerView
{
    [self.tableView reloadData];   // 重新呼叫資料來源即可反映折疊狀態
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

三、專案結構與細節提醒

  • layoutSubviews 會在 frame 改變時被呼叫,是調整子控制項位置的標準位置,但別忘了先呼叫 [super layoutSubviews]。
  • 在 init 系列方法中拿到的 frame 一律是 0。
  • 控制項不顯示時的排查順序:frame 是否為零、hidden 是否為 YES、alpha 是否過低、有沒有被 addSubview、以及父控制項是否有同樣問題。
  • 設定按鈕文字要用 setTitle:forState:,寫成 btn.titleLabel.text = ... 不會生效。
  • 建構子中先呼叫父類並判斷,再初始化自己的屬性。
  • 控制項即將/已經加入父視圖時,分別會呼叫 willMoveToSuperview: 與 didMoveToSuperview。

補充:代理是怎麼設計出來的

當子視圖中的按鈕被點擊,需要請主控制器刷新資料時,有兩種思路。讓子視圖直接持有控制器顯然耦合太重,更好的做法是把「刷新」定義成一個協議,由控制器實作並擔任 delegate。四個步驟:

// 1. 雙方約定協議(命名注意規範)
@protocol YYHeaderViewDelegate <NSObject>
- (void)headerViewDidClickHeaderView:(YYHeaderView *)headerView;
@end

// 2. 視圖中宣告 weak 的 delegate 屬性
@property (nonatomic, weak) id<YYHeaderViewDelegate> delegate;

// 3. 控制器遵守協議並實作方法
@interface YYViewController () <YYHeaderViewDelegate>
- (void)headerViewDidClickHeaderView:(YYHeaderView *)headerView
{
    [self.tableView reloadData];
}

// 4. 把控制器指定為 delegate
headerview.delegate = self;

用 weak 是為了避免視圖與控制器互相持有造成循環引用,這也是 Cocoa 中 delegate 的標準寫法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved