ios - 来自 rightView 的 UITextField 引用

标签 ios swift uibutton uitextfield

我正在将 UIButton 设置为 UITextFieldrightView。此外,我正在设置通过

将目标操作添加到 UIButton
myButton.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)

我想知道如何从指定为 buttonPressed 的方法访问 UITextField,其方法签名如下所示:

func buttonPressed(sender: UIButton) {

}

我试过了

sender.superview as! UITextField

但我似乎得到了一个nil

此外,我无法使用标签,因为它已被用于其他目的。

编辑:

有关详细信息,myButton.addTarget() 发生在 UITableViewCell 内,这就是为什么我没有 outlet View Controller 中的 UITextField

有人有什么想法吗?

最佳答案

你的代码是正确的

我尝试了以下方法,它对我有用

自定义 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)

函数 buttonPressed :

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

点击前

enter image description here

点击 textField 按钮后:

enter image description here

希望您能找到问题所在。

这是 Xcode 6.1 版。因此,我的示例将按照 Swift 1.1。

关于ios - 来自 rightView 的 UITextField 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30797419/

相关文章:

ios - '您的应用缺少对以下 URL 方案 : com . googleusercontent.apps.xxx 的支持'

ios - 在 iOS 上访问图像文件名

ios - 在 Firebase 数据库 Swift 3 中访问嵌套子项

objective-c - UIControlStateHighlighted 的奇怪问题

ios - 为什么在我用代码创建 UIBarButtonItem 时不显示它?

ios - Swift 延迟加载属性 Alamofire 请求

iOS 8 Today 界面生成器

swift - 如何添加一个 Show More/Show Less UIButton 来控制 UITextView

ios - 在几秒钟内重新加载 UiPageViewController

iphone - UIButton 的行为确实很奇怪。崩溃并给出多个错误