0
0

More than 1 year has passed since last update.

UITextViewに入力されている文字数をカウントする

Last updated at Posted at 2022-01-31

TextViewに入力されている文字数のリアルタイムカウントを実装します。
文字列中の全ての空白や改行はカウントしません。

環境

  • Xcode 13.2.1
  • Swift 5.5.2

手順

StringProtocolを拡張します。

Extension.swift
extension StringProtocol where Self: RangeReplaceableCollection {
  var removeWhitespacesAndNewlines: Self {
    filter { !$0.isNewline && !$0.isWhitespace}
  }
}

使用例

ViewController.swift
extension ViewController: UITextViewDelegate {
  func textViewDidChange(_ textView: UITextView) {
    let textLength = textView.text.removeWhitespacesAndNewlines.count
    navigationTitle.text = "total: \(textLength)"
  }
}

終わりに

 
終わりです。

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