#028 How To Lock Screen in iPhone With Your Passcode
the result :
We learn about :
How to Add Alerts in Swift using UIAlertController
Using switch case&for in instead of if-else
Process:
Step1: create [UIImageView]IBOutlet, [UIButton] IBOutlet.
[UIImageView] : showing your passcode
[UIButton] : number buttons
Step2: create IBAction
[UIButton]: input Passcode
[UIButton]: delete number
Step3: create func imageChange ( ) and using switch , for in
To check if the passcodeImageView is filled or not for each index case from 1 to 4, I use a for-in
loop in conjunction with a switch
statement.
Ex:
In the case where the index is 1 (at index 0), the passcodeImageView will be filled, while for other indexes greater than 0, the passcodeImageView will remain hollow. In case 4, the checkPasscode()
function is called to check the passcode. If none of the cases match, the default case will be executed, resulting in all passcodeImageViews being hollow.
Step4: add Alerts in Swift using UIAlertController
func checkPasscode() {
if entercode == passcode {
let controller = UIAlertController(title: "Corret", message: "Welcome Back!", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (_) in
self.reset()
}
controller.addAction(action)
present(controller, animated: true, completion: nil)
}else{
let controller = UIAlertController(title: "Wrong", message: "Please Try Again!", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
controller.addAction(action)
present(controller, animated: true, completion: reset)
}
}
func reset() {
for i in passwordsImageViews {
i.isHighlighted = false
}
entercode = ""
}
Step5: To confirm that the passcodes were not displayed, we can add a print(entercode)
(figure6).
@IBAction func enterpasswords(_ sender: UIButton) {
if entercode.count != 4 {
if let inputNumber = sender.currentTitle {
entercode.append(inputNumber)
}
}
imageChange()
}
Step6: delete number and using dropLast (1)
@IBAction func backwards(_ sender: UIButton) {
if entercode.count != 0 {
entercode = String(entercode.dropLast(1))
imageChange()
}
}
Reference:
Github: