需求很具體:信用卡卡號必須恰好 16 位。不足 16 位時,文字顯示紅色並把送出按鈕停用;一旦達到或超過 16 位,文字轉為黑色,並且不管使用者再怎麼敲,只取前 16 位。
- (void)viewDidLoad {
[super viewDidLoad];
// 每 0.1 秒檢查一次輸入框
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(checkCardInfoInput)
userInfo:nil
repeats:YES];
}
- (void)checkCardInfoInput {
BOOL isValid = YES;
if ([self.cardNumberTextField.text length] >= 16) {
self.cardNumberTextField.textColor = [UIColor blackColor];
// 硬性截斷,只保留前 16 位
self.cardNumberTextField.text =
[self.cardNumberTextField.text substringWithRange:NSMakeRange(0, 16)];
} else {
self.cardNumberTextField.textColor = [UIColor redColor];
isValid = NO;
}
if (isValid) {
self.AddCreditCardButton.enabled = YES;
self.AddCreditCardButton.backgroundColor = [UIColor greenColor];
} else {
self.AddCreditCardButton.enabled = NO;
self.AddCreditCardButton.backgroundColor = [UIColor grayColor];
}
}
邏輯本身很直白:以長度為分支條件,同時驅動「文字顏色」、「內容截斷」與「按鈕啟用狀態」三件事。讓這三者永遠同步,使用者就不會出現「看起來可以送,按下去卻沒反應」的困惑。
老實說,用 0.1 秒的 Timer 輪詢並不是好方案,實務上應該避免。原因有三個。
第一,它是「 polling 」而非「事件驅動」。使用者沒打字時 timer 仍在空轉,白白消耗 CPU 與電力,而且 0.1 秒的間隔本身就代表最多有 100 毫秒的延遲,打字快的人會看到游標跳動。
第二,直接在 timer 回调中重新指派 textField.text,會把游標位置推到尾端。若使用者是在中間插入或刪除字元,輸入位置會突然亂掉。
第三,timer 若沒有在 dealloc 或 viewDidDisappear 中 invalidate,會造成 retain cycle 與背景執行等問題。
更合適的做法是改用 shouldChangeCharactersInRange 在輸入發生的當下攔截:
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
if (textField != self.cardNumberTextField) return YES;
NSString *newText = [textField.text stringByReplacingCharactersInRange:range
withString:string];
if (newText.length > 16) {
return NO; // 直接拒絕這次輸入,游標不會跳
}
// 依 newText.length 即時更新顏色與按鈕狀態
return YES;
}
這個版本沒有輪詢、不會移動游標,也不需要清理 timer。若需要更嚴格的格式控制(例如每四碼自動插入空格、只允許數字),則可再加上自定義的键盘或輸入格式的正則檢核。