🔨
Swift - TextViewに最低/最大入力文字数をつける方法
最低文字数ver
まずは最低文字数をつけたTextViewを実装していきます。
完成イメージ
完成コード
ViewController.swift
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var submitButton: UIButton!
let minLength = 100
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
func textViewDidChange(_ textView: UITextView) {
countLabel.text = "\(minLength - textView.text.count)"
}
@IBAction func submitButtonTapped(_ sender: UIButton) {
if textView.text.count < minLength {
let alert = UIAlertController(title: "文字数が足りません", message: "100文字以上入力してください。", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alert.addAction(okAction)
present(alert, animated: true)
} else {
let alert = UIAlertController(title: "送信しました!", message: "", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alert.addAction(okAction)
present(alert, animated: true)
}
}
}
ポイント
文字数表示の更新
func textViewDidChange(_ textView: UITextView)
この箇所が文字を打ち込むたびに呼び出され、呼び出されるたびに右下のcountLabelを更新しています。
文字数の取得
textView.text.count
このコードでtextViewの現在の文字数を取得して、100文字を超えているときと超えていないときで条件分岐をしています。
最大文字数ver
次に、最大文字数を設定してそれ以上文字を打ち込めなくする機能を実装していきます。
完成イメージ
完成コード
ViewController.swift
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var submitButton: UIButton!
let maxLength = 100
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
func textViewDidChange(_ textView: UITextView) {
countLabel.text = "\(maxLength - textView.text.count)"
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return textView.text.count + (text.count - range.length) <= maxLength
}
@IBAction func submitButtonTapped(_ sender: UIButton) {
let alert = UIAlertController(title: "送信しました!", message: "", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alert.addAction(okAction)
present(alert, animated: true)
}
}
ポイント
文字の追加を止める
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
この箇所が文字を打ち込まれたときに更新するべきかどうかを決めています。
最大文字数に達している場合はreturnすることで、設定した文字数より多く打ち込めないようにしています。
Discussion