Skip to content

Instantly share code, notes, and snippets.

@Josscii
Created June 3, 2020 23:12
Show Gist options
  • Save Josscii/1d70c99788ef5fc798b1a2aa03c01566 to your computer and use it in GitHub Desktop.
Save Josscii/1d70c99788ef5fc798b1a2aa03c01566 to your computer and use it in GitHub Desktop.
UITextField 和 UITextView 限制最大输入长度
import UIKit
class ViewController: UIViewController {
var textField: UITextField!
var textView: UITextView!
private let maxLength = 20
override func viewDidLoad() {
super.viewDidLoad()
textField = UITextField()
textField.addTarget(self, action: #selector(textFieldDidChanged(_:)), for: .editingChanged)
view.addSubview(textField)
textView = UITextView()
textView.delegate = self
view.addSubview(textView)
}
}
extension ViewController {
@objc func textFieldDidChanged(_ textField: UITextField) {
guard textField.markedTextRange == nil else { return }
textField.text = textField.text?.prefix(maxLength).toString()
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
guard textView.markedTextRange == nil else { return }
textView.text = textView.text?.prefix(maxLength).toString()
}
}
extension Substring {
func toString() -> String {
return String(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment