編輯:關於 Android 程式設計
Objective-C 的類目(Category)可以為既有類別補上方法,卻無法直接宣告實例變數與合成屬性。這時候就輪到 Runtime 的「關聯對象(Associated Object)」登場了。
本文以一個實用的例子演練:幫 UITextField 建立類目,讓它在被鍵盤遮住時自動把視圖往上推;順帶加上「點空白處收起鍵盤」的行為。使用方完全不需要額外寫程式碼。
// UITextField+CHTPositionChange.h #import <UIKit/UIKit.h> @interface UITextField (CHTHealper) /** 是否支援視圖上移 */ @property (nonatomic, assign) BOOL canMove; /** 點擊空白時要收起鍵盤、要移動的視圖,預設為當前控制器的 view */ @property (nonatomic, strong) UIView *moveView; /** 輸入框底部與鍵盤頂部之間預留的距離 */ @property (nonatomic, assign) CGFloat heightToKeyboard; @property (nonatomic, assign, readonly) CGFloat keyboardY; @property (nonatomic, assign, readonly) CGFloat keyboardHeight; @property (nonatomic, assign, readonly) CGFloat initialY; @property (nonatomic, assign, readonly) CGFloat totalHeight; @property (nonatomic, strong, readonly) UITapGestureRecognizer *tapGesture; @property (nonatomic, assign, readonly) BOOL hasContentOffset; @end
先定義全域唯一鍵作為關聯識別碼,再用 @dynamic 告訴編譯器 setter/getter 由我們手動實作。
static char canMoveKey; static char moveViewKey; @implementation UITextField (CHTHealper) @dynamic canMove; @dynamic moveView;
讀寫方法就是一對 objc_setAssociatedObject 與 objc_getAssociatedObject:
- (void)setCanMove:(BOOL)canMove {
// 參數依序為:關聯對象、關聯鍵、關聯值、關聯策略
objc_setAssociatedObject(self, &canMoveKey, @(canMove), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)canMove {
// 關聯值存的是物件,取出後需轉型
return [objc_getAssociatedObject(self, &canMoveKey) boolValue];
}
// 取得 TextField 左上角在當前 window 中的座標 [self convertPoint:self.bounds.origin toView:[UIApplication sharedApplication].keyWindow]
接著還需要知道鍵盤高度,這只能透過系統通知取得。問題是「何時註冊、何時移除」?最自然的時機是成為/放棄第一響應者的那一刻。
但如果直接覆寫 becomeFirstResponder,就會蓋掉 UITextField 自身的實作,最明顯的後果是「光標消失」。這裡要用到 Runtime 的另一項能力:方法交換(Method Swizzling)。
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL systemSel = @selector(initWithFrame:);
SEL mySel = @selector(setupInitWithFrame:);
[self exchangeSystemSel:systemSel bySel:mySel];
SEL systemSel2 = @selector(becomeFirstResponder);
SEL mySel2 = @selector(newBecomeFirstResponder);
[self exchangeSystemSel:systemSel2 bySel:mySel2];
SEL systemSel3 = @selector(resignFirstResponder);
SEL mySel3 = @selector(newResignFirstResponder);
[self exchangeSystemSel:systemSel3 bySel:mySel3];
SEL systemSel4 = @selector(initWithCoder:);
SEL mySel4 = @selector(setupInitWithCoder:);
[self exchangeSystemSel:systemSel4 bySel:mySel4];
});
[super load];
}
// 交換步驟
+ (void)exchangeSystemSel:(SEL)systemSel bySel:(SEL)mySel {
Method systemMethod = class_getInstanceMethod([self class], systemSel);
Method myMethod = class_getInstanceMethod([self class], mySel);
// 先嘗試動態添加方法:實作內容是「被交換的方法」
BOOL isAdd = class_addMethod(self, systemSel,
method_getImplementation(myMethod), method_getTypeEncoding(myMethod));
if (isAdd) {
// 添加成功代表類中原本沒有這個實作,把系統方法換到這個新位置
class_replaceMethod(self, mySel,
method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
} else {
// 否則直接交換兩個方法的實作
method_exchangeImplementations(systemMethod, myMethod);
}
}
這裡刻意交換了兩組 init 方法(initWithFrame: 與 initWithCoder:),才能同時涵蓋「用程式碼建立」與「用 xib/storyboard 拖出來」的輸入框。
- (instancetype)setupInitWithCoder:(NSCoder *)aDecoder {
[self setup];
return [self setupInitWithCoder:aDecoder];
}
- (instancetype)setupInitWithFrame:(CGRect)frame {
[self setup];
return [self setupInitWithFrame:frame];
}
- (void)setup {
self.heightToKeyboard = 10;
self.canMove = YES;
self.keyboardY = 0;
self.totalHeight = 0;
self.tapGesture = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(tapAction)];
}
成為第一響應者時註冊鍵盤通知並掛上點擊手勢;放棄時移除通知與手勢。這裡的 newBecomeFirstResponder 在交換之後,實際上指向原本的系統實作。
- (BOOL)newBecomeFirstResponder {
// 未指定 moveView 時,預設為當前控制器的 view
if (self.moveView == nil) {
self.moveView = [self viewController].view;
}
// 避免重複掛上同一個手勢
if (![self.moveView.gestureRecognizers containsObject:self.tapGesture]) {
[self moveView].addGestureRecognizer:self.tapGesture;
}
// 重複點擊同一個輸入框,或設定為不可移動時,不再重複註冊
if ([self isFirstResponder] || !self.canMove) {
return [self newBecomeFirstResponder];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(showAction:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hideAction:)
name:UIKeyboardWillHideNotification object:nil];
return [self newBecomeFirstResponder];
}
- (BOOL)newResignFirstResponder {
if ([self.moveView.gestureRecognizers containsObject:self.tapGesture]) {
[self.moveView removeGestureRecognizer:self.tapGesture];
}
if (!self.canMove) {
return [self newResignFirstResponder];
}
BOOL result = [self newResignFirstResponder];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification object:nil];
// 如果是切換到另一個輸入框,鍵盤不會收起,這裡手動復位
[self hideKeyBoard:0];
return result;
}
// 取得當前 TextField 所屬的 controller
- (UIViewController *)viewController {
UIView *next = self;
while (1) {
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
if (next.superview == nil) { break; }
next = next.superview;
}
return nil;
}
- (void)showAction:(NSNotification *)sender {
if (!self.canMove) { return; }
self.keyboardY = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
self.keyboardHeight = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
[self keyboardDidShow];
}
- (void)hideAction:(NSNotification *)sender {
if (!self.canMove || self.keyboardY == 0) { return; }
[self hideKeyBoard:0.25];
}
- (void)keyboardDidShow {
if (self.keyboardHeight == 0) { return; }
// 輸入框在 window 中的 Y 座標
CGFloat fieldYInWindow = [self convertPoint:self.bounds.origin
toView:[UIApplication sharedApplication].keyWindow].y;
// 判斷是否需要上移,以及要移多少
CGFloat height = (fieldYInWindow + self.heightToKeyboard + self.frame.size.height) - self.keyboardY;
CGFloat moveHeight = height > 0 ? height : 0;
[UIView animateWithDuration:0.25 animations:^{
if (self.hasContentOffset) {
// 若 moveView 是 ScrollView,改動 contentOffset
UIScrollView *scrollView = (UIScrollView *)self.moveView;
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x,
scrollView.contentOffset.y + moveHeight);
} else {
CGRect rect = self.moveView.frame;
self.initialY = rect.origin.y;
rect.origin.y -= moveHeight;
self.moveView.frame = rect;
}
self.totalHeight += moveHeight; // 記錄位移量以便復位
}];
}
- (void)hideKeyBoard:(CGFloat)duration {
[UIView animateWithDuration:duration animations:^{
if (self.hasContentOffset) {
UIScrollView *scrollView = (UIScrollView *)self.moveView;
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x,
scrollView.contentOffset.y - self.totalHeight);
} else {
CGRect rect = self.moveView.frame;
rect.origin.y += self.totalHeight;
self.moveView.frame = rect;
}
self.totalHeight = 0;
}];
}
// 點擊空白處收起鍵盤
- (void)tapAction {
[[self viewController].view endEditing:YES];
}
這個例子示範了 Runtime 最常被使用的兩項技巧:以關聯對象替類目「補上屬性」,以及以方法交換在不破壞原實作的前提下插入自己的行為。兩者搭配,就能把原本需要每個頁面重複書寫的鍵盤處理邏輯,收斂成一個引入即用的類目。
提醒一句:方法交換會改變全域行為,實作時務必用 dispatch_once 保證只交換一次,並在交換後的方法內部呼叫「交換後的自己」,否則很容易造成無限遞迴。新專案若使用 Swift,這類需求也可以評估 Combine/ delegate 或自訂 InputAccessoryView 等更直觀的做法。
Android 開發環境搭建常見錯誤與排除方式
第一次架 Android 開發環境,大概都會遇到這幾個問題。把訊息和對應的解法記下來,下次遇到就不必重頭查。 錯誤一:adb 連線中斷 The connection to
Android SQLite 基本操作完整示範
以下示範 SQLite 的增刪改查四大操作,執行結果一律透過 Log 輸出。 首先是 SQLiteOpenHelper 的實作: package com.example
微信開發實戰(7):收貨地址共享接口 V2 完整接入指南
本篇講解如何在微信內的網頁中調起「收貨地址」原生界面,並把用戶填寫的地址取回到自己的頁面。 需要提醒的是,收貨地址共享接口在 2016 年 4 月 13 日進行過一次升
Android 關於 ListView 的優化問題
今天和朋友一起研究了一些 ListView 的優化方案,整理出來與大家分享。 第一點:ViewHolder 寫成靜態類 ListView 數據加載時經常用到的 ViewH