2017-08-22 51 views
1

我看了看周围的计算器,我一直没有找到解决这个问题的方法。我添加了代码,按照键盘的高度来移动视图。这适用于iOS默认键盘,但是,这不适用于自定义键盘。这是我的代码:视图不能自定义键盘高度 - swift

import UIKit 

class AddCategoryViewController: UIViewController { 

var partialView: CGFloat { 
    return UIScreen.main.bounds.height - 150 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.view.backgroundColor = UIColor.white 

} 

func keyboardWillShow(notification: NSNotification) { 
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { 
     if self.view.frame.origin.y == partialView { 
      let offset: CGSize = ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)! 

      if keyboardSize.height == offset.height { 
       UIView.animate(withDuration: 0.1, animations: {() -> Void in 
        self.view.frame.origin.y -= keyboardSize.height 
       }) 
      } else { 
       UIView.animate(withDuration: 0.1, animations: {() -> Void in 
        self.view.frame.origin.y += keyboardSize.height - offset.height 
       }) 
      } 
     } 
    } 
} 

func keyboardWillHide(notification: NSNotification) { 
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { 
     if self.view.frame.origin.y != partialView { 
      self.view.frame.origin.y += keyboardSize.height 
     } 
    } 
} 

override func viewDidDisappear(_ animated: Bool) { 
    super.viewDidDisappear(animated) 
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window) 
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window) 
} 

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 

    UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.2, options: [.allowUserInteraction], animations: { 
     let frame = self.view.frame 
     self.view.frame = CGRect(x: 0, y: self.partialView, width: frame.width, height: frame.height) 

    }, completion: nil) 

    NotificationCenter.default.addObserver(self, selector: #selector(AddCategoryViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
    NotificationCenter.default.addObserver(self, selector: #selector(AddCategoryViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 
} 
} 

希望你能帮助我解决这个问题,以便视图推高自定义键盘的高度。

+1

尝试改变''UIKeyboardFrameBeginUserInfoKey到'UIKeyboardFrameEndUserInfoKey' – Tj3n

+0

@ Tj3n - 这似乎不起作用。你有什么其他的建议? – ajayb

回答

0

不改变theView的框架..只是改变视图的翻译

UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.2, options: [.allowUserInteraction], animations: { 
    self.view.transform = CGAffineTransform(translationX : 0 , y : partialView) 

}, completion: nil) 

并重置它只是用

self.view.transform = CGAffineTransform.identity