在返回键[UITextField]上隐藏键盘并在之后调用功能

时间:2012-11-21 19:40:42

标签: objective-c ios ios6

所以我只想在用户按下UITextField上的返回键时,键盘被隐藏,然后它调用一个函数。现在我有:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField == _currentPasswordField)
    {
        [textField resignFirstResponder];
        [_passwordField becomeFirstResponder];
        return YES;
    }
    else if (textField == _passwordField)
    {
        [textField resignFirstResponder];
        [_confirmPasswordField becomeFirstResponder];
        return YES;
    }
    else
    {
        [textField resignFirstResponder];
        [self changePassword];
        return YES;
    }
}

但是在整个changePassword函数返回后,键盘会被隐藏。如何隐藏它然后调用我的功能?!

谢谢!

1 个答案:

答案 0 :(得分:0)

问题是你的changePassword方法需要很长时间才能运行,因为它正在通过网络与服务器通信。

所有用户界面更新(例如键盘隐藏动画)都是从主线程触发的。在主线程上调用慢速方法时,可以防止发生这些用户界面更新。

您需要将呼叫从主线程移到changePassword。有很多方法可以做到这一点。最简单的方法之一是使用Grand Central Dispatch(GCD),如下所示:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self changePassword];
});

但是,除非你的changePassword方法是线程安全的,否则这是不安全的,所以你需要考虑你在changePassword中正在做什么,以及它在后台线程上运行会发生什么而其他方法正在主线程上运行。

您需要阅读Concurrency Programming Guide,或观看部分WWDC视频,例如会话211 - 使用WWDC 2010的Grand Central Dispatch简化iPhone App开发。