所以我有一个非常简单的应用程序,我正在尝试构建。它基本上是一个可滚动的文本字段,填满整个屏幕。
当用户点击屏幕时,会出现键盘,您可以在点击的行上开始编辑。
如果您点击键盘将要出现的区域,textView
的大小会缩小,因此您不会在键盘后面输入文字。
到此为止所做的一切都有效。我把代码放在底部。
当用户完成编辑时,屏幕右上角有一个'Done'
按钮,当他们按下时,键盘应该消失,如果文本的数量大于适合的数量在屏幕上,无论他们编辑哪一行都应该在屏幕的底部。
现在,无论我尝试什么,当我resignFirstResponder
隐藏键盘时,textView
会将contentOffset
重置为(0,0)
当我在上面的视图中时,我按完了,这就是结果:
我想要发生的是我编辑的位置在屏幕的底部,如下所示:
类变量,因此可以从文件中的任何位置访问它们
var textField: UITextView = UITextView()
var withKeyboard: NSLayoutConstraint!
var withoutKeyboard: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(textField)
textField.scrollEnabled = true
textField.selectable = true
textField.bounces = true
textField.contentMode = UIViewContentMode.Bottom
textField.setTranslatesAutoresizingMaskIntoConstraints(false)
self.withoutKeyboard = NSLayoutConstraint(item: self.textField, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
self.view.addConstraint(NSLayoutConstraint(item: self.textField, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
self.view.addConstraint(self.withoutKeyboard)
self.view.addConstraint(NSLayoutConstraint(item: self.textField, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.textField, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
}
func keyboardWillShow(notification: NSNotification){
doneButton.hidden = false
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
keyboardHeight = keyboardSize.height
self.withKeyboard = NSLayoutConstraint(item: self.textField, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -keyboardHeight)
self.view.removeConstraint(withoutKeyboard)
self.view.addConstraint(withKeyboard)
textField.layoutIfNeeded()
}
}
func keyboardWillHide(notification: NSNotification){
self.doneButton.hidden = true
self.textFieldOffset = self.textField.contentOffset.y - self.keyboardHeight
println(self.textFieldOffset)
self.view.removeConstraint(withKeyboard)
self.view.addConstraint(withoutKeyboard)
textField.layoutIfNeeded()
textField.contentOffset.y = self.textFieldOffset
}
func donePressed(){
textField.resignFirstResponder()
createRecord()
}
我制定了withKeyboard
和withoutKeyboard
约束条件,以便我可以在键盘出现/消失时取出一个并添加另一个。
无论如何,当我点击完成按钮时,它会将视图重置为最顶层。这不是所有的代码,它只是给我带来麻烦的部分。