您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 控件實作:UITextField 輸入框、佔位文字與即時字數統計

編輯:iOS 相關資訊

前言

UITextField 用來接收單行文字輸入,是表單類介面的核心控件。它支援佔位文字、左右裝飾視圖、邊框樣式,並透過 UITextFieldDelegate 提供完整的輸入生命週期回呼。

案例一:建立基本的輸入框

@synthesize myTextField;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    CGRect textFieldFrame = CGRectMake(0.0f, 0.0f, 200.0f, 31.0f);
    self.myTextField = [[UITextField alloc] initWithFrame:textFieldFrame];

    self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.myTextField.textAlignment = UITextAlignmentCenter;
    self.myTextField.text = @"Sir Archy Develop_Zhang";
    self.myTextField.center = self.view.center;

    [self.view addSubview:self.myTextField];
}

案例二:佔位文字、左側圖示與即時字數統計

@synthesize myTextField;
@synthesize labelCounter;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    CGRect textFieldFrame = CGRectMake(38.0f, 30.0f, 220.0f, 31.0f);
    self.myTextField = [[UITextField alloc] initWithFrame:textFieldFrame];
    self.myTextField.delegate = self;
    self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    // 沒有輸入內容時顯示的提示文字
    self.myTextField.placeholder = @"Enter text here......";
    [self.view addSubview:myTextField];

    // 把統計 label 放在輸入框下方
    CGRect labelCounterFrame = self.myTextField.frame;
    labelCounterFrame.origin.y += textFieldFrame.size.height + 10;
    self.labelCounter = [[UILabel alloc] initWithFrame:labelCounterFrame];
    [self.view addSubview:labelCounter];
    [self calculateAndDisplayTextFieldLengthWithText:self.myTextField.text];

    // 以本地貨幣符號作為左側裝飾視圖
    UILabel *currencyLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    currencyLabel.text = [[[NSNumberFormatter alloc] init] currencySymbol];
    currencyLabel.font = self.myTextField.font;
    [currencyLabel sizeToFit];

    self.myTextField.leftView = currencyLabel;
    self.myTextField.leftViewMode = UITextFieldViewModeAlways;

    /* UITextFieldViewMode 選項:
       UITextFieldViewModeNever           — 從不顯示
       UITextFieldViewModeWhileEditing    — 編輯時顯示
       UITextFieldViewModeUnlessEditing   — 非編輯時顯示
       UITextFieldViewModeAlways          — 一律顯示
    */
}

// 依文字長度切換單複數並更新統計
- (void)calculateAndDisplayTextFieldLengthWithText:(NSString *)paramText {
    NSString *characterOrCharacters = @"Characters";
    if ([paramText length] == 1) {
        characterOrCharacters = @"Character";
    }
    self.labelCounter.text = [NSString stringWithFormat:@"%lu %@",
                              (unsigned long)[paramText length], characterOrCharacters];
}

// 每次即將變更文字時觸發,回傳 NO 可攔截輸入
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
    BOOL result = YES;
    if ([textField isEqual:self.myTextField]) {
        NSString *wholeText = [textField.text stringByReplacingCharactersInRange:range
                                                                     withString:string];
        [self calculateAndDisplayTextFieldLengthWithText:wholeText];
    }
    return result;
}

// 按下鍵盤上的 Return 時收起鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

執行結果

實務提醒

shouldChangeCharactersInRange:replacementString: 是攔截輸入的最佳位置——它讓你在文字真正進入 textField 之前就看到「變更後的完整字串」,因此很適合用來做字數限制、格式檢查或敏感字元過濾。相對地,若搭配 NotificationCenter 的 UITextFieldTextDidChangeNotification,你拿到的是變更「之後」的結果,攔截的難度較高。

另外,borderStyle 自 iOS 7 起在 iOS 系統上視覺效果已大幅弱化。若需要精確的外觀控制,建議改用 layer.borderWidth、layer.cornerRadius 與 layer.borderColor 直接操作圖層。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved