您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 微博仿作重構筆記:用繼承消滅四種 Cell 的重複程式碼

編輯:iOS 相關資訊

功能做完之後回頭看程式碼,最容易刺眼的就是重複。這篇記錄一次針對微博列表 Cell 的重構:把四種 cell 的共同部分抽成父類,讓子類只負責差異。

一、問題:四種 cell,大量複製貼上

微博列表實際上有四種形態:純文字、帶圖片、轉發不帶圖、轉發帶圖。最初每種各寫一份,共同邏輯(頭像、暱稱、時間格式化、文字 assign)被抄了四遍。改一個地方要改四次,這就是該重構的訊號。

二、抽出父類 TextTableViewCell

把「所有 cell 都有的部分」放進父類,並對外提供兩個入口:接收字典、接收一個回呼 block。

// TextTableViewCell.h
#import <UIKit/UIKit.h>

// 用於把 cell 內按鈕的 tag 回傳給列表
typedef void (^MyCellBlock) (UITableViewCell *cell, int tag);

@interface TextTableViewCell : UITableViewCell
-(void)setMyCellBlock:(MyCellBlock)block;
-(void)setDic:(NSDictionary *)dic;
@end

實作中,時間格式轉換是共同瓶頸,一次寫好即可:

-(void)setDic:(NSDictionary *)dic {
    // 頭像
    [self.headImage setImageWithURL:[NSURL URLWithString:dic[@"user"][@"profile_image_url"]]];

    // 暱稱
    self.nameLabel.text = dic[@"user"][@"name"];

    // 時間:先解析成 NSDate,再轉成目標格式
    NSDateFormatter *iosDateFormater = [[NSDateFormatter alloc] init];
    iosDateFormater.dateFormat = @"EEE MMM d HH:mm:ss Z yyyy";
    iosDateFormater.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSDate *date = [iosDateFormater dateFromString:dic[@"created_at"]];

    NSDateFormatter *resultFormatter = [[NSDateFormatter alloc] init];
    [resultFormatter setDateFormat:@"MM月dd日 HH:mm"];
    self.dateLabel.text = [resultFormatter stringFromDate:date];

    // 正文
    self.weiboTextLabel.text = dic[@"text"];
}

// 以 block 把按鈕 tag 往外拋
- (IBAction)tapCellButton:(id)sender {
    UIButton *button = sender;
    self.block(self, button.tag);
}

這裡有兩個關鍵點。一是 locale 必須設為 en_US,否則伺服器給的英文日期字串會解析失敗——這是很容易卡住半天的細節。二是用 block 取代 delegate 來回傳按鈕事件,列表那邊不必再寫一長串 tag 判斷,也不必有型別轉換的困擾。

三、第二種:帶圖片的 cell

只需要繼承父類,加上一個 imageView 並補一行赋值:

@interface ImageTableViewCell ()
@property (strong, nonatomic) IBOutlet UIImageView *contentImage;
@end

@implementation ImageTableViewCell
-(void)setDic:(NSDictionary *)dic {
    [super setDic:dic];     // 先讓父類處理共同部分
    [self.contentImage setImageWithURL:[NSURL URLWithString:dic[@"thumbnail_pic"]]];
}
@end

原本幾十行的內容縮成十行,這就是重構的收益。

四、第三種:轉發但不帶圖

這一類的差異在於正文高度不固定,需要用 Auto Layout 動態調整約束:

-(void)setDic:(NSDictionary *)dic {
    [super setDic:dic];

    // 先移除舊的高度約束
    [self removeConstraint:self.textHeightConstraint];

    // 依文字內容算出所需高度
    NSString *text = dic[@"text"];
    NSDictionary *attrs = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
    CGRect frame = [text boundingRectWithSize:CGSizeMake(260, 1000)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:attrs context:nil];

    // 建立新的高度約束
    NSString *heightValue = [NSString stringWithFormat:@"V:[_weiboTextLabel(%lf)]", frame.size.height + 10];
    NSArray *constraint = [NSLayoutConstraint constraintsWithVisualFormat:heightValue
                                                                 options:0
                                                                 metrics:nil
                                                                   views:NSDictionaryOfVariableBindings(_weiboTextLabel)];
    self.textHeightConstraint = constraint[0];
    [self addConstraint:self.textHeightConstraint];

    self.weiboTextLabel.text = text;
    self.reTextView.text = dic[@"retweeted_status"][@"text"];
}

「移除舊約束、算高度、加新約束」這三步,是所有自適應高度 cell 的固定套路。

五、第四種:轉發且帶圖

只比第三種多一張圖,繼續繼承即可:

-(void)setDic:(NSDictionary *)dic {
    [super setDic:dic];
    [self.contentImageView setImageWithURL:
        [NSURL URLWithString:dic[@"retweeted_status"][@"thumbnail_pic"]]];
}

六、順手解決的兩個問題

重構後可以清楚看到,轉發頁與評論頁的介面幾乎一致,因此用同一個 ViewController 承載,只依按鈕決定要呼叫哪個 API:

if ([self.tag isEqualToValue:@2]) {
    [self post:comments_create Content:@"comment"];
}
if ([self.tag isEqualToValue:@1]) {
    [self post:repost_test Content:@"status"];
}

另外,轉發頁有 textView 需要輸入,鍵盤彈出時若沒有工具列可收,使用者會卡住。解法是加一個 inputAccessoryView:

UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                       target:self action:@selector(tapDone:)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil action:nil];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil action:nil];
toolBar.items = @[item2, item1, item3];
self.commentsTextView.inputAccessoryView = toolBar;

- (IBAction)tapDone:(id)sender {
    [self.commentsTextView resignFirstResponder];
}

七、這次重構的三個心得

第一,判斷該不該抽父類的依據是「差異是否只在少數幾個欄位」。這裡四種 cell 的差異確實集中在一兩個子視圖,很適合繼承;若差異分散在版面結構本身,用組合或設定不同的 xib 反而更清楚。

第二,把時間格式化、URL 圖片載入這類「每個 cell 都要做」的工作收攏到父類,是收益最高的一步,因為它們最容易出現實作不一致。

第三,用 block 取代 delegate 回傳 cell 內事件,能大幅降低列表頁的判斷分支。這在 cell 種類多的頁面尤其明顯。

補充一點:範例中的 setDic: 是早期常見的寫法,在今日的專案中更常使用 model 屬性加上 FMDB/SDWebImage 這類函式庫,並以 prepareForReuse 中清空舊內容來避免 cell 重用的殘影問題。這是最容易在重構後出現的 bug,值得特別檢查。

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