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

iOS UI 開發:用 UITableView 打造簡易 QQ 好友列表(二)實作程式碼

編輯:iOS 開發綜合

本篇承接上一篇的架構說明,直接進入實作程式碼。整體分成資料模型、視圖、控制器三大塊。

一、資料模型部分

YYQQGroupModel.h

#import 

@interface YYQQGroupModel : NSObject
/** 名稱屬性 */
@property (nonatomic, copy) NSString *name;
/** 是否在線 */
@property (nonatomic, copy) NSString *online;
/** 好友列表 */
@property (nonatomic, strong) NSArray *friends;
// 記錄當前組是否要打開
@property (nonatomic, assign, getter = isOpen) BOOL open;

-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)qqGroupModelWithDict:(NSDictionary *)dict;
@end

YYQQGroupModel.m

#import "YYQQGroupModel.h"
#import "YYFriendsModel.h"

@implementation YYQQGroupModel
-(instancetype)initWithDict:(NSDictionary *)dict {
    if (self = [super init]) {
        // 將字典轉換為模型
        [self setValuesForKeysWithDictionary:dict];
        // 定義一個陣列保存轉換後的模型
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:self.friends.count];
        for (NSDictionary *dict in self.friends) {
            YYFriendsModel *friends = [YYFriendsModel friendsWithDict:dict];
            [models addObject:friends];
        }
        _friends = [models copy];
    }
    return self;
}

+(instancetype)qqGroupModelWithDict:(NSDictionary *)dict {
    return [[self alloc] initWithDict:dict];
}
@end

YYFriendsModel.h

#import 

@interface YYFriendsModel : NSObject
/** 每個好友的名稱 */
@property (nonatomic, copy) NSString *name;
/** 每個好友的頭像 */
@property (nonatomic, copy) NSString *icon;
/** 每個好友的個性簽名 */
@property (nonatomic, copy) NSString *intro;
/** 該好友是否是 VIP */
@property (nonatomic, assign, getter = isVip) BOOL vip;

-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)friendsWithDict:(NSDictionary *)dict;
@end

YYFriendsModel.m

#import "YYFriendsModel.h"

@implementation YYFriendsModel
-(instancetype)initWithDict:(NSDictionary *)dict {
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+(instancetype)friendsWithDict:(NSDictionary *)dict {
    return [[self alloc] initWithDict:dict];
}
@end

二、視圖部分

YYfriendCell.h

#import 
@class YYFriendsModel;

@interface YYfriendCell : UITableViewCell
@property (nonatomic, strong) YYFriendsModel *friends;
+(instancetype)cellWithTableview:(UITableView *)tableView;
@end

YYfriendCell.m

#import "YYfriendCell.h"
#import "YYFriendsModel.h"

// 私有擴充
@interface YYfriendCell ()
@end

@implementation YYfriendCell

+(YYfriendCell *)cellWithTableview:(UITableView *)tableView {
    static NSString *identifier = @"qq";
    YYfriendCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        // 這裡使用系統自帶的樣式
        cell = [[YYfriendCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        NSLog(@"創建一個 cell");
    }
    return cell;
}

-(void)setFriends:(YYFriendsModel *)friends {
    _friends = friends;
    // 1. 設置頭像
    self.imageView.image = [UIImage imageNamed:_friends.icon];
    // 2. 設置暱稱
    self.textLabel.text = _friends.name;
    // 3. 設置簡介
    self.detailTextLabel.text = _friends.intro;
    // 判斷是否是會員
    // 注意點:如果不寫 else 設為黑色,會怎樣?
    if (_friends.isVip) {
        [self.textLabel setTextColor:[UIColor redColor]];
    } else {
        [self.textLabel setTextColor:[UIColor blackColor]];
    }
    // 調整字體大小
    self.textLabel.font = [UIFont systemFontOfSize:15.f];
    self.detailTextLabel.font = [UIFont systemFontOfSize:10.f];
}
@end

YYHeaderView.h

#import 
@class YYQQGroupModel, YYHeaderView;

// 約定一個協議
@protocol YYHeaderViewDelegate 
-(void)headerViewDidClickHeaderView:(YYHeaderView *)headerView;
@end

@interface YYHeaderView : UITableViewHeaderFooterView
@property (nonatomic, strong) YYQQGroupModel *group;
// 提供一個類方法,創建頭部視圖
+(instancetype)headerWithTableView:(UITableView *)tableView;
// delegate 遵守 YYHeaderViewDelegate 協議,即可使用協議中的方法
@property (nonatomic, weak) id delegate;
@end

YYHeaderView.m

#import "YYHeaderView.h"
#import "YYQQGroupModel.h"

@interface YYHeaderView ()
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) UILabel *lab;
@end

@implementation YYHeaderView

// 創建自定義的分組頭部視圖
+(instancetype)headerWithTableView:(UITableView *)tableView {
    static NSString *indentifier = @"header";
    // 先到緩存池取資料
    YYHeaderView *headerview = [tableView dequeueReusableCellWithIdentifier:indentifier];
    // 若無,則自行創建
    if (headerview == nil) {
        headerview = [[YYHeaderView alloc] initWithReuseIdentifier:indentifier];
    }
    return headerview;
}

#warning 注意:在構造方法中為控制項設置的 frame 是無效的
-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    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];
        // 圖片不填滿整個 imageView
        btn.imageView.contentMode = UIViewContentModeCenter;
        // 超出範圍的圖片不裁切
        btn.imageView.layer.masksToBounds = NO;
        [self addSubview:btn];
        self.btn = btn;

        // 創建線上 count 的 label
        UILabel *lab = [[UILabel alloc] init];
        lab.textAlignment = NSTextAlignmentRight;
        lab.textColor = [UIColor grayColor];
        [self addSubview:lab];
        self.lab = lab;
    }
    return self;
}

-(void)btnOnclick:(UIButton *)btn {
    NSLog(@"按鈕被點擊了");
    // 1. 修改模型數據
    self.group.open = !self.group.isOpen;
    // 2. 通知代理刷新表格
    if ([self.delegate respondsToSelector:@selector(headerViewDidClickHeaderView:)]) {
        [self.delegate headerViewDidClickHeaderView:self];
    }
}

// frame 改變時會自動呼叫,可在此設置控制項 frame
-(void)layoutSubviews {
#warning 一定不要忘記呼叫父類方法
    [super layoutSubviews];
    self.btn.frame = self.bounds;

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

#pragma mark - 控制項被加入其它視圖時會呼叫以下方法
- (void)didMoveToSuperview {
    NSLog(@"已經添加到視圖了");
    // 此時可拿到最新加入 tableview 的頭部視圖,修改它的小三角
    if (self.group.isOpen) {
        self.btn.imageView.transform = CGAffineTransformMakeRotation(M_PI_2);
    }
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    NSLog(@"將要添加到視圖了");
}

// 重寫 setter,設置數據
-(void)setGroup:(YYQQGroupModel *)group {
    _group = group;
    #warning 設置按鈕文字時一定要指定狀態,否則不顯示
    [self.btn setTitle:_group.name forState:UIControlStateNormal];
    // 設置線上 count
    self.lab.text = [NSString stringWithFormat:@"%@/%d", _group.online, _group.friends.count];
}
@end

三、控制器部分

YYViewController.h

#import 

@interface YYViewController : UITableViewController
@end

YYViewController.m

#import "YYViewController.h"
#import "YYQQGroupModel.h"
#import "YYfriendCell.h"
#import "YYFriendsModel.h"
#import "YYHeaderView.h"

@interface YYViewController () 
/** 用來保存所有的分組數據 */
@property (nonatomic, strong) NSArray *groupFriends;
@end

@implementation YYViewController

#pragma mark - 懶加載
-(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) {
            YYQQGroupModel *group = [YYQQGroupModel qqGroupModelWithDict:dict];
            [models addObject:group];
        }
        _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];
    // 該組打開時回傳實際行數,收攏時回傳 0
    if (group.isOpen) {
        return group.friends.count;
    } else {
        return 0;
    }
}

// 每組每行的內容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YYfriendCell *cell = [YYfriendCell cellWithTableview:tableView];
    YYQQGroupModel *group = self.groupFriends[indexPath.section];
    YYFriendsModel *friends = group.friends[indexPath.row];
    cell.friends = friends;
    return cell;
}

#pragma mark - 代理方法
// 分組標題進入視野時呼叫
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    YYHeaderView *headerview = [YYHeaderView headerWithTableView:tableView];
    headerview.delegate = self;
    YYQQGroupModel *groupmodel = self.groupFriends[section];
    headerview.group = groupmodel;
    return headerview;
}

#pragma mark - YYHeaderViewDelegate
-(void)headerViewDidClickHeaderView:(YYHeaderView *)headerView {
    // 重新呼叫數據源刷新
    [self.tableView reloadData];
}

// 設置分組頭部高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

#pragma mark 隱藏狀態欄
-(BOOL)prefersStatusBarHidden {
    return YES;
}
@end

以上即為好友列表的核心實作,重點在於分組展開/收攏的切換,以及自訂 Header 透過代理回傳點擊事件。

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