与UITextfield的委托方法shouldChangeCharactersInRange并行使用时,UIControlEventEditingChanged不会被触发

时间:2018-03-23 18:39:05

标签: ios objective-c cocoa uitextfield

我在获取文本字段的import json #take input from the user num = int(input("Enter a number: ")) # prime numbers are greater than 1 if num > 1: #check for factors prime_numbers = [] not_prime = [] for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) not_prime.append(num) break else: prime_numbers.append(num) print(num,"is a prime number") fh = open("my_json.json", "a+") fh.write(json.dumps({"prime": prime_numbers, "not_prime": not_prime})) # added an extra ')'.. code will now work fh.close() 事件时遇到问题。

这是代码:

UIControlEventEditingChanged

然后这个方法:

[_txtNum1 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

当我不在委托方法下面实施文本字段时,这是完全致电 -(void)textFieldDidChange :(UITextField *) textField{}

textFieldDidChange

当我平行使用textfield的委托方法- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 时,它不会为shouldChangeCharactersInRange触发事件,只会获取textFieldDidChange的事件。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你必须设置

 self.textfield.delegate = self;
如果此方法返回NO

,则不会调用

更改方法

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

    return YES;
}

答案 1 :(得分:1)

@DhavalBhimani我刚刚创建了一个新应用程序并获取了一个文本字段并为其分配了委托。只需复制您的代码并将其粘贴到我的演示中。它似乎工作。你可以查看下面的代码。也许你错过了什么..

- (void)viewDidLoad {
    [super viewDidLoad];
    [_txtDemo addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

-(void)textFieldDidChange:(UITextField *)textField
{
    NSLog(@"called");
}

#pragma mark - textfield methods

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"string = %@",string);
    return YES;
}
  

2018-03-24 00:27:35.292771 + 0530演示目标C [783:14964] string = h

     

2018-03-24 00:27:35.382728 + 0530演示目标C [783:14964]称为

     

2018-03-24 00:27:39.851133 + 0530演示目标C [783:14964] string = i

     

2018-03-24 00:27:39.869326 + 0530演示目标C [783:14964]称为