2017-08-22 70 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