7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift 電話番号入力時自動スペース

Last updated at Posted at 2017-01-19

UITextFieldを使って電話番号を入力する際に、自動的に半角スペースを追加させる。

イメージ

movie2.gif

repository

実現方法

##actionの定義
ViewControllerにて、EditingChanged用のアクション関数を定義する.

@IBAction func edit() {
}

##actionとUITextFieldの関連
storyboardで、UITextFieldのEditingChangedアクションとaction関数を関連させる.
スクリーンショット 2017-01-19 18.09.56.png

##action中身の実装
UITextFieldの入力値に対して、スペースを挿入・削除処理を実施する.

@IBOutlet weak var telTf : UITextField!
var currentLength = 0
    
@IBAction func edit() {
    guard let text = telTf.text else {return}
    let length = text.characters.count
        
    if (length > currentLength) {
        // when add text.
        if (length == 4 || length == 9) {
            let content = NSMutableString(string: text)
            content.insert(" ", at: length - 1)
            telTf.text = content as String
        }
    } else {
        // when delete text.
        if (length == 4 || length == 9) {
            telTf.text = (text as NSString).substring(to: length - 1)
        }
    }
        
    currentLength = length
}
7
4
1

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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?