这可能是一个简单的问题,但我一直在测试这个测试项目中的一个问题的许多不同解决方案,现在我在编辑textView
字段时无法通过完成按钮来重新设置键盘。< / p>
当用户点击开始编辑时,我的代码应该从键盘后面移动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)
}
}
答案 0 :(得分:1)
在viewDidLoad中将VC指定为textview委托,并使用&#39; shouldChangeTextInRange&#39; 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
}