尝试设置 UITextField 文本时执行选择器

发布于 2024-09-26 11:33:06 字数 528 浏览 3 评论 0原文

每当执行 UIControlEventEditingChanged 事件时,我都会尝试清除 UITextField。

但是,当我将文本设置为空时,UIControlEventEditingChanged 事件将再次被调用,并且这就是它继续进行的方式。

这是我的代码:

- (void)updateText {
    //other code
    textfield.text = @"";
    //other code
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [textfield addTarget:self action:@selector(updateText) forControlEvents:UIControlEventEditingChanged];
}

我希望能够设置文本字段的文本,而不会无限循环!

任何帮助表示赞赏。

i'm trying to clear a UITextField whenever the UIControlEventEditingChanged event is being performed.

However, when I set the text to nothing, the UIControlEventEditingChanged event is being called again, and this is the way it keeps going.

This is my code:

- (void)updateText {
    //other code
    textfield.text = @"";
    //other code
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [textfield addTarget:self action:@selector(updateText) forControlEvents:UIControlEventEditingChanged];
}

I would like to be able to set the text of the text field without it looping infinitely!

Any help appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

巷子口的你 2024-10-03 11:33:06

不确定这是最好的方法,但在对文本字段进行编程更新之前,您可以删除 UIControlEventEditingChanged 侦听器,然后再次添加它。

Not sure this is the best way, but before you do your programmatic update to the textfield you could remove your UIControlEventEditingChanged listener and then add it again afterwards.

寂寞笑我太脆弱 2024-10-03 11:33:06

do

- (void)updateText {
    //other code
    if (![textfield.text isEqualToString:@""]){
       textfield.text = @"";
    }
    //other code
}

it 可能不是最优雅的解决方案,但它非常快并且肯定会起作用

do

- (void)updateText {
    //other code
    if (![textfield.text isEqualToString:@""]){
       textfield.text = @"";
    }
    //other code
}

it is probably not the most elegant solution but it is very quick and will surely work

落花浅忆 2024-10-03 11:33:06

注销事件并重新注册的另一种方法是放入一个 BOOL 来防止这种特定的递归。

@interface MyClass : () {
    BOOL clearText;
}

并在方法中:

- (void)updateText {
    if (clearText){
        clearText = NO;
        return;
    }
    //other code
    clearText = YES;
    textfield.text = @"";
    //other code
}

An alternative to deregistering for the event, and reregistering is to put in a BOOL to guard against this particular recursion.

@interface MyClass : () {
    BOOL clearText;
}

and in the method:

- (void)updateText {
    if (clearText){
        clearText = NO;
        return;
    }
    //other code
    clearText = YES;
    textfield.text = @"";
    //other code
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文