限制文本个数

public class MyTextField: UITextField {

    let maxLength = 6
    //MARK:重写
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        p_setUpTextField()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        p_setUpTextField()
    }
    //MARK:私有方法
    private func p_setUpTextField(){
        addTarget(self, action: #selector(p_textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
    }
    
    @objc private func p_textFieldDidChange(textField : UITextField) {
        
        guard let selectedRange = markedTextRange  else {
            if text?.count ?? 0 > maxLength {
                text = String((text ?? "").prefix(maxLength))
            }
            return
        }
        
        guard let _ = position(from: selectedRange.start, offset: 0)  else {
            if text?.count ?? 0 > maxLength {
                text = String((text ?? "").prefix(maxLength))
            }
            return
        }
    }
}

你可能感兴趣的:(限制文本个数)