UITextField

  • addTarget方法:
#import "ViewController.h"

@interface ViewController () 
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 开始编辑
    [self.textField addTarget:self action:@selector(tfBeginEditing) forControlEvents:   UIControlEventEditingDidBegin];
    // 结束编辑
    [self.textField addTarget:self action:@selector(tfEndEditing) forControlEvents:   UIControlEventEditingDidEnd];
    // 正在编辑
    [self.textField addTarget:self action:@selector(tfEditingChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 退出键盘
    [self.view endEditing:YES];
}

#pragma mark - 监听textField的事件
- (void)tfBeginEditing
{
    NSLog(@"开始编辑");
}

- (void)tfEndEditing
{
    NSLog(@"结束编辑");
}

- (void)tfEditingChange:(UITextField *)tf
{
    NSLog(@"tfEditingChange--%@",tf.text);
}

@end
  • 代理方法:
#import "ViewController.h"

@interface ViewController () 
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.textField.delegate = self;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 退出键盘
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"开始编辑");
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"结束编辑");
}

/**
 *  当textField文字发生改变就会调用这个方法
 *  @param string    用户输入的文字
 *
 *  @return YES:允许用户输入;NO:禁止用户输入
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"shouldChangeCharactersInRange--%@",string);
    if([string isEqualToString:@"1"]) {
        return NO;
    }
    return YES;
}

@end

你可能感兴趣的:(UITextField)