2017-03-24 112 views
1

我有以下功能,使鍵盤不覆蓋TextView,但鍵盤顯示不正確。相反,出現了一種沒有鍵盤按鍵的全黑「鍵盤」。鍵盤沒有正確顯示

func textViewDidBeginEditing(_ textView: UITextView) { 
    moveTextView(textView, moveDistance: -250, up: true) 
} 

func textViewDidEndEditing(_ textView: UITextView) { 
    moveTextView(textView, moveDistance: -250, up: false) 
} 

func textViewShouldReturn(_ textView: UITextView) -> Bool { 
    textView.resignFirstResponder() 
    return true 
} 

func moveTextView(_ textView: UITextView, moveDistance: Int, up: Bool) { 
    let moveDuration = 0.3 
    let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance) 

    UIView.beginAnimations("animateTextView", context: nil) 
    UIView.setAnimationBeginsFromCurrentState(true) 
    UIView.setAnimationDuration(moveDuration) 
    self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement) 
    UIView.commitAnimations() 
} 

難道有人對於爲什麼以及如何解決它有一個想法嗎?

謝謝你的時間。

回答

1

試着以另一種方式做到這一點。將UITextViewDelegate添加到您的viewController。添加水木清華這樣在viewDidLoad中():

self.yourTextView1.delegate = self 
self.yourTextView2.delegate = self 

//For scrolling the view if keyboard on 
NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 

並添加到您的ViewController:

var keyBoardAlreadyShowed = false //using this to not let app to scroll view 
//if we tapped UITextField and then another UITextField 
func keyboardWillShow(notification: NSNotification) { 
    if !keyBoardAlreadyShowed { 
     self.view.frame.origin.y -= 50 // we will scroll on it 
     keyBoardAlreadyShowed = true 
    } 
} 

func keyboardWillHide(notification: NSNotification) { 
    self.view.frame.origin.y += 50 
    keyBoardAlreadyShowed = false 
} 

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    self.view.endEditing(true) 
} 

希望它可以幫助

+0

嗨,謝謝你的評論。爲什麼'UITextFieldDelegate'而不是'UITextViewDelegate'? – alberzyzz

+1

@alberzyzz是的。抱歉。如果你使用textView使用UITextViewDelegate –

+0

鍵盤不顯示,並在視圖的頂部創建一個黑色的空間,增加每次我點擊textView – alberzyzz

0

試試這個:

iPhone模擬器>還原內容和設置。

清理項目,然後重新啓動Xcode。