iOS - 以编程方式调用shouldChangeCharactersInRange

时间:2016-12-13 09:24:00

标签: ios uitextfield

我有一个文本字段和一个委托方法shouldChangeCharactersInRange。在这种方法中,a有一个自定义逻辑。

我想以编程方式设置textField.text,以及如何调用shouldChangeCharactersInRange

我该怎么做?

默认情况下,设置textField.text方法shouldChangeCharactersInRange后未调用

1 个答案:

答案 0 :(得分:0)

添加" UITextFieldDelegate"到你的班级并设置:

textField.delegate = self;

ViewController.m:

#import "ViewController.h"

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

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.textField.delegate = self;
    self.textField.text = @"Hello World";
    [self textField:self.textField shouldChangeCharactersInRange:NSMakeRange(0, self.textField.text.length-1) replacementString:self.textField.text];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    return YES;
}
@end