這一則把三個在微博式客戶端裡很常一起出現的技巧打包記錄:系統自帶的下拉刷新控件、用 colorWithPatternImage 做背景平鋪、以及把新資料插進既有陣列的頭部並配上提示動畫。
- (void)viewDidLoad {
[super viewDidLoad];
[self setupRefresh];
}
/** 建立下拉刷新 */
- (void)setupRefresh {
UIRefreshControl *control = [[UIRefreshControl alloc] init];
// 只有使用者手動下拉才會觸發 UIControlEventValueChanged
[control addTarget:self
action:@selector(refreshStateChange:)
forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:control];
// 進入刷新狀態。注意:這只是顯示轉圈動畫,不會觸發事件
[control beginRefreshing];
// 因此要手動呼叫一次來載入資料
[self refreshStateChange:control];
}
這裡有個很多人會忽略的細節:beginRefreshing 只改變視覺狀態,不會觸發 action。所以 App 首次啟動若想自動帶入刷新動畫,必須自己再呼叫一次处理方法。
/**
UIRefreshControl 進入刷新狀態:載入最新資料
*/
- (void)refreshStateChange:(UIRefreshControl *)control {
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 拼接請求參數
HWAccount *account = [HWAccountTool account];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"access_token"] = account.access_token;
// 帶入目前最新一筆的 ID,只取比它更新的資料
HWStatus *firstStatus = [self.statuses firstObject];
if (firstStatus) {
params[@"since_id"] = firstStatus.idstr;
}
[mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json"
parameters:params
success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
NSArray *newStatuses = [HWStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
// 把新資料插到陣列最前面
NSRange range = NSMakeRange(0, newStatuses.count);
NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
[self.statuses insertObjects:newStatuses atIndexes:set];
[self.tableView reloadData];
[control endRefreshing];
[self showNewStatusCount:newStatuses.count];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
HWLog(@"請求失敗 - %@", error);
[control endRefreshing];
}];
}
since_id 是微博 API 的增量語意:帶這個參數時只回傳 ID 比它大的貼文,也就是時間更晚的內容。這比每次抓全量再自己比對省下大量頻寬。
insertObjects:atIndexes: 搭配 NSIndexSet 是一次性批次插入,比反覆呼叫 insertObject:atIndex: 有效率得多,而且索引不會互相影響。
/**
顯示最新微博數量
@param count 新微博筆數
*/
- (void)showNewStatusCount:(int)count {
// 1. 建立 label
UILabel *label = [[UILabel alloc] init];
// colorWithPatternImage: 專為平鋪場合設計,
// 會用一張小圖重複鋪滿整個 view 作為背景
label.backgroundColor = [UIColor colorWithPatternImage:
[UIImage imageNamed:@"timeline_new_status_background"]];
label.width = [UIScreen mainScreen].bounds.size.width;
label.height = 35;
// 2. 其他屬性
if (count == 0) {
label.text = @"沒有新的微博資料,稍後再試";
} else {
label.text = [NSString stringWithFormat:@"共有 %d 條新的微博資料", count];
}
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
label.font = [UIFont systemFontOfSize:16];
// 3. 加到導航控制器的 view 上,並壓在導航列下方
label.y = 64 - label.height;
[self.navigationController.view insertSubview:label
belowSubview:self.navigationController.navigationBar];
// 4. 動畫:先往下移一個 label 高度,停留 1 秒,再收回
CGFloat duration = 1.0;
[UIView animateWithDuration:duration animations:^{
label.transform = CGAffineTransformMakeTranslation(0, label.height);
} completion:^(BOOL finished) {
CGFloat delay = 1.0;
// UIViewAnimationOptionCurveLinear 表示等速
[UIView animateWithDuration:duration
delay:delay
options:UIViewAnimationOptionCurveLinear
animations:^{
label.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {
[label removeFromSuperview];
}];
}];
}
程式碼註解裡點出了關鍵:當一個動畫結束後要回到「執行前的狀態」時,用 transform 比改 frame 或 center 更合適。原因是 transform 是相對於原始 frame 的變換矩陣,設回 CGAffineTransformIdentity 就等於完全復原,不必去記住或重算原本的座標值。改 frame 則需要自己保存與還原舊值,容易出錯。
另外 transform 動畫只觸發合成(compositing),不觸發 layout,效能上比改 frame 好。
label.y = 64 - label.height 這裡的 64 是「狀態列 20 + 導航列 44」的合計。在支援多種裝置尺寸之後,這種寫死數字的做法會出問題,建議改用 UIApplication.shared.statusBarFrame.size.height 加上 navigationController.navigationBar.bounds.size.height 來計算。