Fawxy / CBPinEntryView

A customisable view for entering arbitrary length pins, codes or passwords in iOS. Supports iOS 12 one time codes.
MIT License
189 stars 41 forks source link

How to set the text Value to the CBPinEnteryView? #19

Open hassan8055 opened 5 years ago

hassan8055 commented 5 years ago

I'm using this library for CNIC . Now i have to set the text to your Pin view (CNIC value coming from server). I'm looking to set the value just like the textfield.text but haven't found anything. if there is anything to set the text to Pin view . kindly let me know.

vikasAccion commented 5 years ago

Is this possible now to prefill PIN?

Fawxy commented 5 years ago

There isn't currently but I can definitely see the use in this. I'll have a think about how to implement this best - with the codebase as it is currently I think it could end up quite messy!

Or if anyone wants to open a PR...

vikasAccion commented 5 years ago

There isn't currently but I can definitely see the use in this. I'll have a think about how to implement this best - with the codebase as it is currently I think it could end up quite messy!

Thanks

musa-almatri commented 5 years ago

@vikasAccion @hassan8055 Here is a workaround extension to set the pin, till a proper fix is done on the repo.

extension CBPinEntryView {

    open func setPin(_ pin: String) {
        self.clearEntry()
        /// String(pin.prefix(length)) to remove any extra characters
        String(pin.prefix(length)).forEach {
            _ = self.textField(self.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: String($0))
            self.textField.insertText(String($0))
        }
        if pin.count >= length {
            self.resignFirstResponder()
        }
    }

}

Usage

 pinEntryView.setPin(text: "123456")
vikasAccion commented 5 years ago

@vikasAccion @hassan8055 Here is a workaround extension to set the pin, till a proper fix is done on the repo.

extension CBPinEntryView {
    func setPin(text: String) {
        if let innerTextField = (self.subviews.compactMap { $0 as? UITextField }).first {
            self.clearEntry()
            text.forEach {
                _ = self.textField(innerTextField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: String($0))
                innerTextField.insertText(String($0))
            }
        }
    }
}

Usage

 pinEntryView.setPin(text: "123456")

Thanks Musa. Thanks a lot. It saved my day.