ios - becomeFirstResponder 非常慢

标签 ios objective-c uitextfield

我有以下 viewDidLoad 方法:

- (void)viewDidLoad {
    NSLog(@"didLoad");
    if (self.loginField.text.length > 0) [self.passwordField becomeFirstResponder];
    else [self.loginField becomeFirstResponder];
}

我还在 viewWillAppearviewDidAppear 中添加了日志时间。

在某些情况下,推送动画会花费很多时间。我测量了带有注释(和没有)if-else 行的时间(参见:时间如下所示)。我不知道在 viewWillAppearviewDidAppear 调用之间什么会减慢我的应用程序。

我尝试使用 Time Profiler (Instruments) 分析这段代码,但它什么也没显示。我不知道我该怎么做才能更快地展示我的观点。有什么想法吗?

使用 becomeFirstResponder,第一次调用

2014-07-11 16:51:41.090 didLoad
2014-07-11 16:51:41.133 willAppear
2014-07-11 16:51:44.223 did appear
diffAppear = 3090ms

使用 becomeFirstResponder,第二次调用

2014-07-11 16:52:01.370 didLoad
2014-07-11 16:52:01.400 willAppear
2014-07-11 16:52:02.109 did appear
diffAppear = 709ms

没有becomeFirstResponder,先调用

2014-07-11 16:57:21.720 didLoad
2014-07-11 16:57:21.754 willAppear
2014-07-11 16:57:22.420 did appear
diffAppear = 666ms

没有becomeFirstResponder,第二次调用

2014-07-11 16:57:31.851 didLoad
2014-07-11 16:57:31.870 willAppear
2014-07-11 16:57:32.541 did appear
diffAppear = 671ms

最佳答案

作为评论中的@holex 提及:

the –becomeFirstResponser normally loads the input views for the actual object which takes time. on the other hand, you should call this method after your view is in the navigation stack and in the view-hierarchy properly, which means in that case: in or after the –viewDidAppear: method, not sooner.

我将 –becomeFirstResponser 移动到了 -viewDidAppear:。现在根据这个question我添加了这些观察者,如下所示,现在是应用程序。

- (void)willShowKeyboard:(NSNotification *)notification {
    [UIView setAnimationsEnabled:NO];
}

- (void)didShowKeyboard:(NSNotification *)notification {
    [UIView setAnimationsEnabled:YES];
}

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willShowKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didShowKeyboard:) name:UIKeyboardDidShowNotification object:nil];

这不是一个完美的解决方案(推送动画没有键盘)但对我来说已经足够了。

关于ios - becomeFirstResponder 非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24701220/

相关文章:

ios - 我如何有效地为 100 多个 View Controller 使用多个 Storyboard?

objective-c - ABMultiValueRef nil 值检查

ios - 检查 collectionView 中的文本字段是否为空

xcode - 准备 Segue 后 UiTextField 没有变化

objective-c - MKPolyline 不会显示

javascript - 使用 EvaluateJavaScript 单击按钮意外行为

ios - 仅支持设备的 SDK

iphone - UIScrollView 和内容需要触摸移动事件

python - 程序退出结束时 pyobjc 和 wx 崩溃

ios - 如何确定刚刚在 Collection View 中编辑了哪个单元格的文本字段?