2015-10-15 48 views
0

這可能是一個簡單的問題,但我一直在測試這個測試項目中的一個問題的很多不同的解決方案,現在當我編輯我的textView字段時,我無法獲得完成按鈕來辭職鍵盤。爲什麼我的完成鍵不會退出鍵盤?

當用戶點擊開始編輯時,我的代碼應該從鍵盤後面移動textView。然後,完成後,用戶應該能夠點擊完成鍵並隱藏鍵盤並將textView移回到視圖的底部。在此代碼中,點擊屏幕將會退出鍵盤並將textView移動到其原始位置。問題是,當我在編輯textView時點擊完成時,它會插入回車符。

看來像我在SO中看過她的其他問題都是針對Objective-C的。我正在使用Swift 2.感謝您的幫助。

import UIKit 

class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate { 

@IBOutlet var textViewField: UITextView! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    textViewField.layer.cornerRadius = 10 
} 

func textViewDidBeginEditing(textView: UITextView) { // became first responder 

    //move textView up 
    let myScreenRect: CGRect = UIScreen.mainScreen().bounds 
    let keyboardHeight : CGFloat = 250 

    UIView.beginAnimations("animateView", context: nil) 
    //var movementDuration:NSTimeInterval = 0.35 
    var needToMove: CGFloat = 0 

    var frame : CGRect = self.view.frame 
    if (textView.frame.origin.y + textView.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight)) { 
     needToMove = (textView.frame.origin.y + textView.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight); 
    } 

    frame.origin.y = -needToMove 
    self.view.frame = frame 
    UIView.commitAnimations() 
} 

func textViewDidEndEditing(textView: UITextView) { 
    //move textfields back down 
    UIView.beginAnimations("animateView", context: nil) 
    var frame : CGRect = self.view.frame 
    frame.origin.y = 0 
    self.view.frame = frame 
    UIView.commitAnimations() 
} 

//function to hide keyboard when Done key tapped for textField 
func textFieldShouldReturn(textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    return true 
} 

//funtion to hide keyboard when screen is tapped 
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    self.view.endEditing(true) 
} 

} 
+1

文本視圖不叫了UITextFieldDelegate方法。 – rmaddy

回答

1

分配VC在viewDidLoad中TextView的委託並使用 'shouldChangeTextInRange' 的TextView代表

override func viewDidLoad() { 
    super.viewDidLoad() 
    textField.delegate = self 
    textViewField.layer.cornerRadius = 10 
} 

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { 
    if(text == "\n") { //return key pressed 
     textView.resignFirstResponder() 
     return false 
    } 
    return true 
} 
+0

op正在使用文本視圖,而不是文本字段。 – rmaddy

+1

對不起,只是編輯了文本視圖的代碼 – Lukas

+0

謝謝盧卡斯。這完全符合我的希望。 – Greg

相關問題