UITextField の文字を選択済みにする
Focus 当たったら下記の画像のような状態になっててほしい。
textField.selectAll
selectAll
というメソッドで実現できる。
引数に self
を渡すと、コピーとかカットの選択肢が表示される。
textField.selectAll(nil)
textField.selectAll(self)
2 回に 1 回しか選択済みにならない問題
textField に Focus が当たった時に選択済みにするために、 UITextFieldDelegate
を使い下記のように書いていた。
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.selectAll(nil)
}
ただし、この書き方だと 2 回に 1 回しか選択済みになってくれない。
その時は、下記のように遅延させて selectAll すると上手くいく。
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.perform(#selector(selectAll(_:)), with: nil, afterDelay: 0.1)
// 選択肢出したい場合はこっち
// textField.perform(#selector(selectAll(_:)), with: self, afterDelay: 0.1)
}
本当なら dispatch 的なので書いたほうが良いかもしれないが、今のところ afterDelay で動作には問題無い。
参考
iphone - selectall uitextfield does not always select all - Stack Overflow