LoginSignup
3
1

More than 3 years have passed since last update.

Swift ナビゲーションバーにUITextVIewの文字数をリアルタイムにカウント

Last updated at Posted at 2019-08-28

完成形

ナビゲーションバーのタイトル下にTextViewに入力された文字数をリアルタイムにカウント

count.gif

実装の流れ

1. UITextViewDelegateを継承

ViewController: UIViewController, UITextViewDelegate {

2. 文字数をカウントしたいUITextViewにデリゲート設定

MemoTextView.delegate = self

3. ナビゲーションバーのタイトル・カウントの作成

イメージは下記のような形
青い四角:全体のUIView
黄色の四角:タイトルラベル
緑の四角:カウントラベル

qiita_material_count1.png

        //青い四角 UIView
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 40))

        //黄色の四角 タイトルラベル
        let titleLabel = UILabel()
        titleLabel.text = "メモ"
        titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
        titleLabel.frame = CGRect(x: 30, y: 0, width: 50, height: 20)

        //緑の四角 カウントラベル
        countLabel.text = "0"
        countLabel.font = UIFont.systemFont(ofSize: 14)
        countLabel.frame = CGRect(x: 40, y: 20, width: 50, height: 20)

        //UIViewに追加
        titleView.addSubview(countLabel)
        titleView.addSubview(titleLabel)
     
        //ナビゲーションに青い四角のUIViewを追加
        navigationItem.titleView = titleView

4. TextViewの文字数をカウントラベルに挿入

デリゲートメソッドであるtextViewDidChangeを用意し、下記のように文字列にキャストして、カウントラベルに値を入れます。

    func textViewDidChange(_ textView: UITextView) {
        let MemoCount = MemoTextView.text.count
        countLabel.text = String(MemoCount)
    }
3
1
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
3
1