Search code examples
iosswiftuibuttonuitextfieldpasscode

How to implement passcode logic to the screen


Hello i am creating Swift app and i want to make a screen similar to passcode lock in iphone in which we can add numbers in the textfield by pressing buttons. The problem is that i am not able to get the logic for the specific layout.

this is how the layout looks :-

the grey boxes are UITextFields and light blue are buttons.

Below is the code so far:-

@IBOutlet var numberPadButtons: [UIButton]!
   
@IBOutlet var txtFields: [UITextField]! 

@IBAction func numbPadBtnsTapped(_ sender: UIButton) {
        //Unable to implement the logic
    }

buttons and textfields have tags (0-10 & 1 to 4).


Solution

  • [Update Answer]

    Basic Passcode Logic in Swift

    @IBOutlet var txtfields: [UITextField]!
    var passcode:[String] = [] //["1","3","5","0"]
    var limit = 4
    
    @IBAction func PressOnBtn(_ sender: UIButton) {
        if sender.tag > 10
        {
            if passcode.count > 0
            {
                self.passcode.removeLast()
                self.txtfields[self.passcode.count].text = ""
            }
        }
        else
        {
            if limit == passcode.count
            {
                return
            }
            self.passcode.append("\(sender.tag)")
            self.filltextfiled()
        }
    }
    
    func filltextfiled()
    {
        for (index,pass) in self.passcode.enumerated()
        {
            self.txtfields[index].text = pass
        }
        
    }