限制UITextField輸入內容的長度,uitextfield長度

來源:互聯網
上載者:User

限制UITextField輸入內容的長度,uitextfield長度

一、前言

  今天做手機號輸入限制長度,例如我的textfield只能輸入11位,如果再多輸入的話就不再textfield中顯示,只顯示11位的手機號。

  如果用ReactiveCocoa的話,這個很好解決。但是項目中沒有引入該類庫,所以只能手動的取完成了。

二、實現原理

  先看代碼:

////  ViewController.m//  Test////  Created by zhanggui on 15/12/28.//  Copyright © 2015年 zhanggui. All rights reserved.//#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UITextField *myTextField;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.myTextField];    self.myTextField.placeholder = @"只能輸入11位哦";    // Do any additional setup after loading the view, typically from a nib.}#pragma mark - UITextFieldDelegate-(void)textFiledEditChanged:(NSNotification *)obj{    UITextField *textField = (UITextField *)obj.object;        NSString *toBeString = textField.text;    if (toBeString.length-1 > 10 && toBeString.length>1) {        textField.text = [toBeString substringToIndex:11];    }}@end

   做法如下:

  首先,我們需要添加一個通知,這個通知的name是:UITextFieldTextDidChangeNotification 。我們可以點擊這個名字進去,會發現

UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;

  這個是在UITextField.h中定義的一個常量字串,他的作用如下:

    通知觀察者textField中的內容改變了,受影響的textField就儲存在通知的object參數中。(Notifies observers that the text in a text field changed. The affected text field is stored in the object parameter of the notification.)

  這樣的話,我們就可以通過通知來控制了。當我們每次輸入字元到textField中的時候,都會在通知的方法中進行監聽,我就在裡面判斷輸入的字串的長度是否滿足需要的條件,如果滿足了條件(我這裡的條件是11位),就讓textField的text始終等於我要限制的長度。以此來完成自己的需求。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.