该项目是改写了 @nixzhu 作者的 KeybaordMan Swift 版本,特此感谢作者 @nixzhu。因为工作需要在 Objective-C 中实现,所以用 Objective-C 重写了一遍,大家各取所需。
我们可能需要从键盘通知中获取键盘信息来完成动画,但是这个方法是复杂的,易于出错。
但是KeyboardRobin将使它变得简单且容易。
#import "KeyboardRobin.h"
使用键盘出现/消失来进行动画
self.keyboardRobin = [[KeyboardRobin alloc] init];
__weak typeof (self) weak_self = self;
self.keyboardRobin.animateWhenKeyboardAppear = ^(NSInteger appearPostIndex, CGFloat keyboardHeight, CGFloat keyboardHeightIncrement) {
NSLog(@"Keyboard appear: appearPostIndex:%@, keyboardHeight:%@, keyboardHeightIncrement:%@", @(appearPostIndex), @(keyboardHeight), @(keyboardHeightIncrement));
//update tableView's contentOffset
CGPoint tempContentOffset = weak_self.tableView.contentOffset;
tempContentOffset.y += keyboardHeightIncrement;
weak_self.tableView.contentOffset = tempContentOffset;
//update tableView's contentInset
UIEdgeInsets tempInset = weak_self.tableView.contentInset;
tempInset.bottom = keyboardHeight + CGRectGetHeight(weak_self.toolBar.frame);
weak_self.tableView.contentInset = tempInset;
//update toolBar's bottom constraint relative to superview
weak_self.toolBarBottomConstraint.constant = keyboardHeight;
[weak_self.view layoutIfNeeded];
};
self.keyboardRobin.animateWhenKeyboardDisappear = ^(CGFloat keyboardHeight) {
NSLog(@"Keyboard disappear: keyboardHeight:%@", @(keyboardHeight));
//update tableView's contentOffset
CGPoint tempContentOffset = weak_self.tableView.contentOffset;
tempContentOffset.y -= keyboardHeight;
weak_self.tableView.contentOffset = tempContentOffset;
//update tableView's contentInset
UIEdgeInsets tempInset = weak_self.tableView.contentInset;
tempInset.bottom = CGRectGetHeight(weak_self.toolBar.frame);
weak_self.tableView.contentInset = tempInset;
//update toolBar's bottom constraint relative to superview
weak_self.toolBarBottomConstraint.constant = 0;
[weak_self.view layoutIfNeeded];
};
有关更具体的信息,您可以使用KeyboardRobin发布的keyboardInfo
self.keyboardRobin.postKeyboardInfo = ^(KeyboardRobin *keyboardRobin, KeyboardInfo keyboardInfo) {
// TODO
}
查看示例以获取更多信息。
原作者的中文介绍。
您可以将KeyboardRobin.h
和KeyboardRobin.m
拖动到您的iOS项目中。但推荐使用CocoaPods。
KeyboardRobin可在MIT许可协议下使用。请参阅LICENSE文件以获取更多信息。