2015-06-18 39 views
0

因此,我實現了一個位於屏幕底部的文本字段。一旦用戶點擊文本字段,鍵盤出現,文本字段也很好地坐在鍵盤的頂部(如那些聊天應用程序)Swift iOS - 如何讓文本字段在關閉和打開時根據預測文本移動

但是,一旦我滑動預測文本打開或關閉(向上或向下)視圖混亂,並且它不再坐在鍵盤上。我該如何解決這個問題?

到目前爲止,這是我的代碼:

class ViewController: UIViewController, UITextFieldDelegate { 

    @IBOutlet var textField: UITextField! 
    var _currentKbHeight: CGFloat = 0.0 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.textField.delegate = self 
    } 

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

     NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) 
     NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillChange:"), name: UIKeyboardWillChangeFrameNotification, object: nil) 
    } 

    func textFieldShouldReturn(textField: UITextField) -> Bool { 
     textField.resignFirstResponder() 
     return true 
    } 

    override func viewWillDisappear(animated: Bool) { 
     super.viewWillDisappear(animated) 

     NSNotificationCenter.defaultCenter().removeObserver(self) 
    } 

    func keyboardWillChange(notification: NSNotification) { 
     if let userInfo = notification.userInfo { 
      if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { 

       var deltaHeight:CGFloat = keyboardSize.height - _currentKbHeight 

       UIView.animateWithDuration(0.3, animations: { 
        self.view.frame = CGRectOffset(self.view.frame, 0, -deltaHeight) 
       }) 

       _currentKbHeight = keyboardSize.height 
      } 
     } 
    } 


    func keyboardWillHide(notification: NSNotification) { 
     if let userInfo = notification.userInfo { 
      if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { 

       UIView.animateWithDuration(0.3, animations: { 
        self.view.frame = CGRectOffset(self.view.frame, 0, keyboardSize.height) 
       }) 

       _currentKbHeight = 0.0 

      } 
     } 
    } 
} 

enter image description here enter image description here enter image description here

回答

0

實際上,你想覆蓋inputAccessoryView財產。這是蘋果公司內置的方式,可以提供像您的視圖一樣的視圖,始終位於鍵盤之上。

下面是一個例子:https://robots.thoughtbot.com/input-accessorizing-uiviewcontroller

又如:http://derpturkey.com/uitextfield-docked-like-ios-messenger/

+0

所以我還是看完文章後,感到困惑。首先,我必須創建一個由文本字段組成的工具欄。然後在我的viewcontroller我不得不重寫inputAccessoryView,但通過這樣做,我得到錯誤。在哪裏私人讓accessoryView = AccessoryView(frame:CGRectZero)'AccessoryView'類來自? – jonprasetyo

+0

我相信你只是讓視圖控制器上的一個屬性,你想要它的介紹。 – AdamPro13

相關問題