Posted at

iOSでキーボードのアニメーションを止める方法

More than 5 years have passed since last update.

iOSのアプリでキーボードの出現や消滅のアニメーションを止めると、動作がキビキビになります。その方法を共有します。


ObjectiveC

@interface ViewController : UIViewController

@end

@implementation ViewController
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
}

-(void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidHideNotification
object:nil];
}

static BOOL needRevert;

-(void) keyboardWillShow:(NSNotification*)notif
{
needRevert = [UIView areAnimationsEnabled];
[UIView setAnimationsEnabled:NO];
}

-(void) keyboardDidShow:(NSNotification*)notif
{
if (needRevert) [UIView setAnimationsEnabled:YES];
}

- (void)keyboardWillHide:(NSNotification*)notif
{
needRevert = [UIView areAnimationsEnabled];
[UIView setAnimationsEnabled:NO];
}

- (void)keyboardDidHide:(NSNotification*)notif
{
if (needRevert) [UIView setAnimationsEnabled:YES];
}

@end