键盘处理的方式有很多种,这里总结出两种一种三方框架,一种通过NSNotificationCenter监听的方式
- 三方框架-> 导入IQKeyboardManager,只需要在运行方法里写一句话。
//导入头文件
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//就这一句
IQKeyboardManager.sharedManager().enable = true
return true
}
}
- NSNotificationCenter监听的方式
//这个是UItextFile的下间距,做成属性
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomMargin;
- (void)setupBase
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 监听
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
// 修改约束
CGFloat keyboardY = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
self.bottomMargin.constant = screenH - keyboardY;
// 执行动画
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
<h1>一招平天下!!!</h1>