首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITextField 雙欄位驗證:同時有內容顯示 Alert、否則繼續流程

     編輯:程式設計綜合問答

實作邏輯

監聽文字變更(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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved