監聽文字變更(UIControlEventEditingChanged)或按鈕點擊時,檢查兩個 UITextField 是否皆有輸入。
- (IBAction)nextButtonTapped:(id)sender {
if ([txt1.text length] > 0 && [txt2.text length] > 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"兩個欄位皆已填寫"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
} else {
// 繼續下一步流程
[self performSegueWithIdentifier:@"goNext" sender:self];
}
}
UIAlertController 取代已棄用的 UIAlertView (iOS 8+)。UITextFieldDelegate 即時啟用/停用按鈕:- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
BOOL bothFilled = [txt1.text length] > 0 && [txt2.text length] > 0;
nextButton.enabled = bothFilled;
return YES;
}