美文网首页
iOS 键盘上处理

iOS 键盘上处理

作者: 张三儿 | 来源:发表于2017-03-30 14:10 被阅读18次

键盘处理的方式有很多种,这里总结出两种一种三方框架,一种通过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>

相关文章

网友评论

      本文标题:iOS 键盘上处理

      本文链接:https://www.haomeiwen.com/subject/ebauottx.html