LoginSignup
8
5

More than 5 years have passed since last update.

UITextField に Focus が当たった時に、文字を選択済みの状態にする

Last updated at Posted at 2016-11-27

UITextField の文字を選択済みにする

Focus 当たったら下記の画像のような状態になっててほしい。

unspecified.png

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

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5