UITextField使用的一些細節

weixin_34377065發表於2014-09-15

UITextField使用的一些細節

這篇博文是我自己使用UITextField的一些總結,並沒有太多營養,並會持續更新。

2014.9.15

--------------------------------------------------------------------------------------------------------------------------------------

原始碼:

//
//  RootViewController.m
//  UITextField
//
//  Created by YouXianMing on 14-9-15.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField *textField;

@end

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _textField                      = [[UITextField alloc] initWithFrame:CGRectMake(10,  80, 300, 40)];
    _textField.layer.borderWidth    = 1.f;
    _textField.layer.borderColor    = [UIColor redColor].CGColor;
    _textField.backgroundColor      = [UIColor whiteColor];
    _textField.textAlignment        = kCTTextAlignmentLeft;    // 左對齊
    _textField.delegate             = self ;
    _textField.keyboardType         = UIKeyboardTypeNumberPad; // 數字鍵盤
    _textField.placeholder          = @"請輸入4位驗證碼";
    _textField.clearsOnBeginEditing = YES;
    
    
    
    // 空出左側邊緣空隙(通過新增一個view來實現)
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10,
                                                            CGRectGetHeight(_textField.bounds))];
    _textField.leftView     = view;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    
    [self.view addSubview:_textField];
    
    // 新增手勢
    [self addGesture];
}

- (void)addGesture
{
    // 手勢
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [self.view addGestureRecognizer:tap];
}

// 限制輸入長度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.location >= 4)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

- (void)tapGesture:(UITapGestureRecognizer *)tap
{
    // 取消第一響應狀態
    [_textField resignFirstResponder];
}

@end

效果:

左側空出空隙

限制輸入長度

--------------------------------------------------------------------------------------------------------------------------------------

 

相關文章