How to set Texfield or Label max length
1. For Max/Min lenght textField or Label
must be same name/ variabel ex: textFiledMin.text
textFiledMin.text = textFiledMin.text?.safelyLimitedTo(length: 3) //if u use this, need code below TextLengthsMax.swift
https://stackoverflow.com/questions/25223407/max-length-uitextfield
only for fields that are in use not for passing data
create new file --> TextLengthsMax.swift
import UIKitprivate var __maxLengths = [UITextField: Int]()extension UITextField {@IBInspectable var maxLength: Int {get {guard let l = __maxLengths[self] else {return 3 // (global default-limit. or just, Int.max)}return l}set {__maxLengths[self] = newValueaddTarget(self, action: #selector(fix), for: .editingChanged)}}@objc func fix(textField: UITextField) {let t = textField.texttextField.text = t?.safelyLimitedTo(length: maxLength)}}extension String{func safelyLimitedTo(length n: Int)->String {if (self.count <= n) {return self}return String( Array(self).prefix(upTo: n) )}}
3. Use viewWillAppear (Passing data)
FirstController to anyController
FirstController to anyController
override func viewWillAppear(_ animated: Bool) {
let userDefault = UserDefaults()
if let data = userDefault.object(forKey: "savePlatMobil") {
if let message = data as? String {
self.platNo.text = message
}
}
platNo.text = platNo.text?.safelyLimitedTo(length: 2)
}
No comments: