I have a sign in screen in which two fields are there password and email textfield.
I added both textfield with stackview. After adding textfields, I need to add button of password lock. After clicking on password lock button user can see the password. I took button from library and try to add on textfield but, due to stackview it always set as third element for stackview. So I am unable to add.
So I decided to add with extension of textfield. So i added button successfully in utility class,
but unable to add action with selector. It showing an error
Value of type ‘UIViewController’ has no member ‘passwordAction’
My code for add button is
extension UITextField {
func passwordButton(vc:UIViewController){
let paddingView = UIView(frame: CGRect(x: 25, y: 25, width: 24, height: 17))
let passwordButton = UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 17))
passwordButton.setImage(UIImage(named: "show_password"), for: .normal)
passwordButton.addTarget(vc, action: #selector(vc.passwordAction), for: .touchUpInside)
paddingView.addSubview(passwordButton)
self.addSubview(paddingView)
}
}
class Loginviewcontroller{
passwordTextField.passwordButton(vc: self)
func passwordAction(){
print("action")
}
}
I am calling this method from login controller.
So I have two question:-
- when two textfield are attached with stackview, we can not put button on textfield with storyboard?
- How can I make globle method to add button and add action that can access in uiviewcontroller?
2
Answers
Error is self explanatory, you added the
passwordAction
method toLoginviewcontroller
but infunc passwordButton
you take aUIViewController
as an argument. As a result even when you pass instance ofLoginviewcontroller
topasswordButton
function call, in the function scopevc
is just anotherUIViewController
and clearly allUIViewController
s does not have a method namedpasswordAction
.As you said you wanna make global method to add button and add action that can access in uiviewcontroller you can follow below approach
Step 1: Declare a protocol
Step 2: Update your
passwordButton
method to takeSecureTextProtocol
instead of plainUIViewController
Step 3: Make your ViewController’s that want to get the button action to confirm to
SecureTextProtocol
protocolThat should do the job
You can always solve this problem with simple code, that’s the way I do it.
then on viewcontroller’s viewdidload just call the functions on your storyboards