Created
June 3, 2020 23:12
-
-
Save Josscii/1d70c99788ef5fc798b1a2aa03c01566 to your computer and use it in GitHub Desktop.
UITextField 和 UITextView 限制最大输入长度
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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