LoginSignup
1
2

More than 3 years have passed since last update.

[Swift]UITextViewで指定の文字数以上入力できないようにする(リアルタイムで入力内容をチェックする)

Last updated at Posted at 2021-02-05

やりたいこと

UITextView内で文字を入力時に、指定の文字数を超えて入力できないようにする。

ちなみに、この処理方法を応用すれば

  • 数字を入力できないようにする
  • スペースや改行を入力できないようにする

などの、リアルタイムで入力をチェックする処理を実装可能かと思います。

実装の流れ

基本的な実装の考え方は以下になります

  • TextViewの内容が変わろうとするときに
  • 入力された変更を加えた後の文字数が140文字を超える場合、入力された変更を受け付けない

下記の流れで実装します。

  1. ViewControllerをUITextViewDelegateプロトコルに準拠させる。
  2. textView(_:,shouldChangeTextIn:replacementText) メソッドを追加する。
  3. textView(_:shouldChangeTextIn:replacementText)メソッド内に、変更後の結果文字数を計算して、140文字以下ならtrue、140文字超ならfalseを返すようにする。

実装方法

前提:UITextViewに文字を入力中に、ラベル内の文字数表示を自動更新する の状態。

RealtimeCountViewController.swift
class RealtimeCountViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var memoTextView: UITextView!
    @IBOutlet weak var countLabel: UILabel!

    let maxCharacterCount = 140

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        memoTextView.delegate = self
    }

    //文字数カウント表示を更新する。
    func textViewDidChange(_ textView: UITextView) {
        countLabel.text = String(format: "%d/%d",textView.text.count, maxCharacterCount)

        if textView.text.count > maxCharacterCount {
            countLabel.textColor = .red
        } else {
            countLabel.textColor = .systemGray
        }
    }

    //文字数が140文字を超えないようにする。
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        //入力された変更を行った場合の文字数を計算。
        let newCharacterCount = textView.text.count - range.length + text.count

        //140文字以下でtrueを返し、140文字超でfalseを返す (手抜き)
        return (newCharacterCount <= maxCharacterCount)
    }

}

動作確認環境

下記2環境で動作を確認しました。

Xcode: 11.7
iOS: 13.7

Xcode: 12.4
iOS: 14.4

以上

1
2
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
1
2