专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
发微博界面toolBar跟随键盘
- 将
toolBar底部约束关联到控制器中,等键盘改变是重新设置约束 
监听键盘frame改变
在
HMComposeViewController的viewDidLoad里面添加UIKeyboardWillChangeFrameNotification通知override func viewDidLoad() { super.viewDidLoad() // 添加键盘frame改变的通知 NotificationCenter.default.addObserver(self, selector: #selector(willChangeFrame(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) textView.delegate = self setNavigationBar() setToolBar() }- 在
HMComposeViewController的deinit里面注销通知// 注销通知 deinit { NotificationCenter.default.removeObserver(self) } - 实现接收通知方法
// MARK: - 键盘frame改变方法 /// 键盘frame改变方法 func keyboardWillChangeFrame(notifiction: NSNotification) { print("notification: \(notifiction)") }
- 更新
toolBar底部约束的值// MARK: - 键盘frame改变方法 /// 键盘改变调用这个通知方法 func willChangeFrame(notification: NSNotification) -> Void { print("notification: \(notification)") } toolBar跟随键盘动画/// 键盘改变调用这个通知方法 func willChangeFrame(notification: NSNotification) -> Void { // 获取键盘最终的frame let endFrameObject = notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject let endFrame = endFrameObject.cgRectValue! // toolBar底部到父控件的底部的距离 = 屏幕高度 - 键盘.frame.origin.y toolBarBottomCons.constant = UIScreen.height - endFrame.origin.y // 获取动画时间 let durationAnyObject = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as AnyObject let duration = durationAnyObject.doubleValue! // toolBar动画 UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } }- 当
键盘正在显示时点击HMComposeViewController的取消按钮,发现需要等到HMComposeViewController完全关闭之后才会关闭键盘,用户体验不是很好.解决方法:在点击取消按钮的时候主动将键盘退下/// 关闭控制器 func close() -> Void { textView.resignFirstResponder() // 关闭控制器 self.dismiss(animated: true, completion: nil) } - 用户点击撰写微博按钮,目的是想发送微博.为了增强用户体验,当一进入
HMComposeViewController在viewDidLoad主动弹出键盘,// 主动弹出键盘 textView.becomeFirstResponder() 发现
toolBar动画有问题, 在viewDidAppear里面主动弹出键盘// view已经显示 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 主动弹出键盘 textView.becomeFirstResponder() }