UITextField reference from rightView

1.9k Views Asked by At

I am setting a UIButton to the rightView of a UITextField. Furthermore, I am setting adding a target-action to the UIButton via

myButton.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)

I would like to know how I can access the UITextField from the method specified as buttonPressed where its method signature looks like:

func buttonPressed(sender: UIButton) {

}

I have tried

sender.superview as! UITextField

but I seem to be getting a nil.

Also, I am unable to use tags as it is already in use for another purpose.

EDIT:

For further information, myButton.addTarget() happens inside a UITableViewCell, which is why I don't have an outlet to the UITextField in the view controller.

Anyone have any ideas?

1

There are 1 best solutions below

2
On

Your code is correct

I tried as follows and it is working for me

Custom textField :

    var textFiled = UITextField(frame: CGRectMake(20.0, 50.0, 100.0, 33.0))
    textFiled.borderStyle = UITextBorderStyle.RoundedRect

    let purpleImageButton = UIButton(frame :CGRectMake(0, 0, 10, 30))
    purpleImageButton.backgroundColor = UIColor.blackColor()
    purpleImageButton.setTitle("T", forState: UIControlState.Normal)
    purpleImageButton.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)
    textFiled.rightViewMode = UITextFieldViewMode.Always
    textFiled.rightView = purpleImageButton
    self.view.addSubview(textFiled)

Function buttonPressed :

func buttonPressed(sender: UIButton) {
    let textF : UITextField = sender.superview as UITextField
    textF.text = "Hello"
}

Before Clicking

enter image description here

After Clicking on button of textField :

enter image description here

Hope you will find the problem.

Here is Xcode version 6.1. So, My example will be as per Swift 1.1.