UITextField基本概念&&限制字符的輸入長度(包括中文字符)

- (void)viewDidLoad
{
    [super viewDidLoad];

    //文本輸入框 UITextField
    UITextField *textField = [[UITextField alloc] init];
    //設置
    textField.frame = CGRectMake(50, 50, 200, 200);

    //設置輸入框中的文本 默認爲空
    textField.text = nil;
    //設置輸入框中的屬性字符串,默認爲空 如果不理解屬性字符串,可以跳過
    textField.attributedText = nil;
    //設置默認的屬性字符串
    textField.defaultTextAttributes = nil;
    //設置默認顯示的屬性字符串
    textField.attributedPlaceholder = nil;
    //設置輸入框的文本顏色,默認爲空,可不設置,因爲系統設置爲黑色
    textField.textColor = [UIColor blackColor];
    //設置背景顏色
    textField.backgroundColor = [UIColor greenColor];
    //設置輸入框的字體,默認爲空,可不設置,系統默認設置12pt
    textField.font = [UIFont systemFontOfSize:18.0];
    //設置背景圖片  只有當設置外框類型爲UITextBorderStyleNone時纔有效
    //textField.background = [UIImage imageNamed:@"1.png"];
    //textField.disabledBackground = [UIImage imageNamed:@"2.png"];

    //設置輸入框變爲密碼框  每輸入一個字符就變成點
    textField.secureTextEntry = NO;
    /*
     typedef NS_ENUM(NSInteger, NSTextAlignment)
     {
     NSTextAlignmentLeft      = 0,      // 左對齊
     #if   iphone
     NSTextAlignmentCenter    = 1,    // 居中
     NSTextAlignmentRight     = 2,    // 右對齊
     #else  ipad
     NSTextAlignmentRight     = 1,    // Visually right aligned
     NSTextAlignmentCenter    = 2,    // Visually centered
     #endif  其他
     NSTextAlignmentJustified = 3,    // 和段落對齊
     NSTextAlignmentNatural   = 4,    // 默認狀態  正常情況下
     } NS_ENUM_AVAILABLE_IOS(6_0);
     */
    //設置輸入框的文字顯示模式
    textField.textAlignment = NSTextAlignmentNatural;
    //設置默認顯示的文字 70%透明度
    textField.placeholder = @"請輸入文字";
    /*
     typedef NS_ENUM(NSInteger, UITextBorderStyle) {
     UITextBorderStyleNone,       //無邊框
     UITextBorderStyleLine,       //方角矩形 實線
     UITextBorderStyleBezel,      //方角矩形 實線
     UITextBorderStyleRoundedRect //圓角矩形 帶有透明度的線條
     };*/
    //設置外框類型
    textField.borderStyle = UITextBorderStyleNone;

    //設置輸入框字體最小值
    textField.minimumFontSize = 18.0;

    //設置爲YES時文本會自動縮小以適應文本窗口大小,默認是保持原來大小,而讓長文本滾動
    textField.adjustsFontSizeToFitWidth = NO;

    /*
     ypedef NS_ENUM(NSInteger, UIKeyboardType) {
     UIKeyboardTypeDefault,                // 默認狀態,支持所有字符
     UIKeyboardTypeASCIICapable,           // 可以輸入ASCII碼
     UIKeyboardTypeNumbersAndPunctuation,  // 數字和標點符號
     UIKeyboardTypeURL,                    // 字母和url(com)
     UIKeyboardTypeNumberPad,              // 數字鍵盤
     UIKeyboardTypePhonePad,               // 數字帶+*# 電話鍵盤
     UIKeyboardTypeNamePhonePad,           // 電話鍵盤支持輸入人名
     UIKeyboardTypeEmailAddress,           // 字母帶@. 輸入電子郵件
     UIKeyboardTypeDecimalPad NS_ENUM_AVAILABLE_IOS(4_1),   // 數字鍵盤帶.
     UIKeyboardTypeTwitter NS_ENUM_AVAILABLE_IOS(5_0),      // 字母帶@#
     UIKeyboardTypeWebSearch NS_ENUM_AVAILABLE_IOS(7_0),    // 字母帶  前往 按鈕
     UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // 可以輸入ASCII碼 首字母大寫

     };
     */
    //設置鍵盤的樣式
    textField.keyboardType = UIKeyboardTypeURL;
    //當再次編輯輸入框時 輸入框的內容就會被清空
    textField.clearsOnBeginEditing = NO;

    //首字母是否大寫
    /*
     typedef NS_ENUM(NSInteger, UITextAutocapitalizationType) {
     UITextAutocapitalizationTypeNone,          //全部小寫
     UITextAutocapitalizationTypeWords,         //每個單詞(中間有空格)的首字母大寫
     UITextAutocapitalizationTypeSentences,     //第一個單詞的首字母大寫
     UITextAutocapitalizationTypeAllCharacters, //全部大寫
     };
     */
    textField.autocapitalizationType = UITextAutocapitalizationTypeNone;

    /*
     輸入框中是否有個叉號,在什麼時候顯示,用於一次性刪除輸入框中的內

     typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
     UITextFieldViewModeNever,         //默認顯示沒有
     UITextFieldViewModeWhileEditing,  //輸入時顯示有叉號
     UITextFieldViewModeUnlessEditing, //不輸入時顯示有叉號
     UITextFieldViewModeAlways         //一直顯示有叉號,
     };
     */
    textField.clearButtonMode = UITextFieldViewModeWhileEditing ;

    /*
     typedef enum {
     UITextAutocorrectionTypeDefault, 默認
     UITextAutocorrectionTypeNo,   不自動糾錯
     UITextAutocorrectionTypeYes,  自動糾錯
     } UITextAutocorrectionType;
     */
    //是否糾錯
    textField.autocorrectionType = UITextAutocorrectionTypeNo;

    /*
     typedef NS_ENUM(NSInteger, UIReturnKeyType) {
     UIReturnKeyDefault,       //return鍵顯示默認狀態 return
     UIReturnKeyGo,            //return鍵顯示Go
     UIReturnKeyGoogle,        //return鍵顯示Search
     UIReturnKeyJoin,          //return鍵顯示Join 加入
     UIReturnKeyNext,          //return鍵顯示next 下一個
     UIReturnKeyRoute,         //return鍵顯示Route
     UIReturnKeySearch,        //return鍵顯示Search 搜索
     UIReturnKeySend,          //return鍵顯示Send 發送
     UIReturnKeyYahoo,         //return鍵顯示Search
     UIReturnKeyDone,          //return建顯示Done
     UIReturnKeyEmergencyCall,
     };
     */
    //設置return鍵的類型
    textField.returnKeyType = UIReturnKeyDefault;

    /*
     typedef NS_ENUM(NSInteger, UIKeyboardAppearance) {
     UIKeyboardAppearanceDefault,          //默認外觀 淺灰色
     UIKeyboardAppearanceDark              //深灰 石墨色
     UIKeyboardAppearanceLight             //淺灰色
     UIKeyboardAppearanceAlert = UIKeyboardAppearanceDark,  // 深灰 石墨色
     };
     */
    //設置鍵盤的外觀
    textField.keyboardAppearance = UIKeyboardAppearanceDefault;

    //設置輸入文字之間位置的view
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1"]];
    image.bounds = CGRectMake(0, 0, 10, 10);
    textField.leftView = image;
    //顯示狀態和 叉號 顯示狀態類似
    textField.leftViewMode = UITextFieldViewModeAlways;
    //設置輸入框內部右側位置的view
    UIImageView *image1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"2"]];
    image1.bounds = CGRectMake(0, 0, 10, 10);
    textField.rightView = image1;
    //顯示狀態和 叉號 顯示狀態類似
    textField.rightViewMode = UITextFieldViewModeAlways;

    textField.delegate = self;

    [self.view addSubview:textField];
}

/*
重寫繪製的各種方法

 //重寫來重置邊緣區域
 - (CGRect)borderRectForBounds:(CGRect)bounds;

 //重寫來重置文字區域
 - (CGRect)textRectForBounds:(CGRect)bounds
  {
    //return CGRectInset(bounds, 50, 0);
    CGRect inset = CGRectMake(bounds.origin.x+190, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
    return inset;
};

 //重寫來重置佔位符區域 也就是默認顯示的區域
 - (CGRect)placeholderRectForBounds:(CGRect)bounds
  {
  //return CGRectInset(bounds, 20, 0);
   CGRect inset = CGRectMake(bounds.origin.x+100, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
   return inset;
};

 //重寫來重置編輯區域
 - (CGRect)editingRectForBounds:(CGRect)bounds
  {
    //return CGRectInset( bounds, 10 , 0 );
   CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width -10, bounds.size.height);
   return inset;
};

 //重寫來重置clearButton位置,改變size可能導致button的圖片失真
 - (CGRect)clearButtonRectForBounds:(CGRect)bounds
  {
   return CGRectMake(bounds.origin.x + bounds.size.width - 50, bounds.origin.y + bounds.size.height -20, 16, 16);
};

 //重寫來重置左邊view區域
 - (CGRect)leftViewRectForBounds:(CGRect)bounds
  {
   CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width-250, bounds.size.height);
   return inset;
    //return CGRectInset(bounds,50,0);
};

 //重寫來重置右邊view區域
 - (CGRect)rightViewRectForBounds:(CGRect)bounds;

 //重寫繪製改變文字屬性,重寫時調用super可以按默認圖形屬性繪製,若自己完全重寫繪製函數,就不用調用super
 - (void)drawTextInRect:(CGRect)rect;

 //重寫繪製改變佔位符屬性,重寫時調用super可以按默認圖形屬性繪製,若自己完全重寫繪製函數,就不用調用super
 - (void)drawPlaceholderInRect:(CGRect)rect
  {
    //CGContextRef context = UIGraphicsGetCurrentContext();
    //CGContextSetFillColorWithColor(context, [UIColor yellowColor].CGColor);
    [[UIColororangeColor] setFill];
    [[selfplaceholder] drawInRect:rectwithFont:[UIFontsystemFontOfSize:20]];
};
 */

#pragma mark - UITextFieldDelegate
//設置輸入框,是否可以被修改
// NO將無法修改,不出現鍵盤
// YES可以修改,默認值
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

//開始編輯時獲得焦點時,執行該方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}

/*
 返回BOOL值,指定是否允許文本字段接觸,當編輯結束,文本字段會讓出first responder
 要想再用戶結束編輯時阻止文本字段消失,可以返回NO
 這對一些文本字段必須始終保持活躍狀態的程序很有用,比如即使消息
 */
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return NO;
}

//文本框結束編輯以後會調用
- (void)textFieldDidEndEditing:(UITextField *)textField
{
}

/*
 當用戶使用自動更正功能,把輸入的文字修改爲推薦的文字時,就會調用這個方法
 這對於想要加入撤銷選項的應用程序特別有用
 可以跟蹤字段內所做的最後一次修改,也可以對所有編輯做日誌記錄,用做審計用途
 要防止文字被改變可以返回NO
 這個方法的參數中又一個NSRange對象,指明瞭被改變文字的位置,建議修改的文本也再其中
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

//返回一個BOOL值指明是否允許根據用戶請求清除內容
//可以設置在特定條件下才允許清除內容
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    return YES;
}

//返回一個BOOL值,指明是否允許在按下回車鍵時結束編輯
//如果允許要調用resignFirstResponder方法,會導致結束編輯,而鍵盤會被手氣
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return YES;
}

================== 限制字符輸入長度================
當你嘗試了各種方法還是不能很好地控制中英文的輸入長度時,希望你能看到這裏的解決方案

#define CourseNameMaxLength 10

//在控件上添加通知事件
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)                                                   name:@"UITextFieldTextDidChangeNotification"                                                      object:cell.coursrNameText];

//離開視圖前別忘了釋放
-(void)dealloc{  
   [[NSNotificationCenter defaultCenter]removeObserver:self                                          name:@"UITextFieldTextDidChangeNotification"                                           object:_albumNameTextField];  
} 

//實現通知方法

-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;

    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 鍵盤輸入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 簡體中文輸入,包括簡體拼音,健體五筆,簡體手寫
        UITextRange *selectedRange = [textField markedTextRange];
        //獲取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制
        if (!position) {
            if (toBeString.length > CourseNameMaxLength) {
                textField.text = [toBeString substringToIndex:CourseNameMaxLength];
            }
        }
        // 有高亮選擇的字符串,則暫不對文字進行統計和限制
        else{

        }
    }
    // 中文輸入法以外的直接對其統計限制即可,不考慮其他語種情況
    else{
        if (toBeString.length > CourseNameMaxLength) {
            textField.text = [toBeString substringToIndex:CourseNameMaxLength];
        }  
    }  
}
發佈了22 篇原創文章 · 獲贊 4 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章