だから私は構築しようとしている非常に単純なアプリを持っています。基本的には、画面全体を埋めるスクロール可能なテキスト フィールドです。
ユーザーが画面をタップすると、キーボードが表示され、タップした行から編集を開始できます。
キーボードが表示される領域をタップすると、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
、キーボードが表示/非表示になるたびに、一方を取り外してもう一方を追加できるようにしました。
とにかく、完了ボタンを押すと、ビューが一番上にリセットされます。これはすべてのコードではなく、問題を引き起こしている部分にすぎません。