【问题标题】:Adding action to a button which is added to a textfield by extension in swift向按钮添加操作,该按钮通过 swift 扩展名添加到文本字段
【发布时间】:2017-10-18 13:03:34
【问题描述】:

我必须通过扩展在文本字段右侧添加一个按钮

代码是---

import UIKit
@IBDesignable class TxtFieldCustom: UITextField {
 @IBInspectable var rightButtonImage: UIImage?
    {
    didSet
    {
        updateRightView()
    }
}
func updateRightView()
    {
        //for right Image
        if let image = rightButtonImage
        {
  let button = UIButton(type: .custom)
            button.setImage(image, for: .normal)
            button.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0)
            button.frame = CGRect(x: 0, y: 0, width: 29, height: 29)
rightView = button
            rightViewMode = .always

        } else
        {
            rightViewMode = UITextFieldViewMode.never
            rightView = nil
        }
    }

按钮显示为屏幕截图,但我很困惑如何为该按钮设置操作。我无法在扩展文件中设置它,因为我对不同的文本字段有不同的操作...

【问题讨论】:

标签: swift uibutton uitextfield


【解决方案1】:

您可以为按钮设置一个目标,当调用该操作时,您应该发布这样的通知:

NotificationCenter.default.post(name: NSNotification.Name.init("buttonPressed"), object: nil)

然后在您的 ViewController 中,您可以添加一个观察者并实现不同的操作。 使用多个 UITextFields,您可以通过通知传递 userData。

【讨论】:

  • 谢谢...我也这样做了。 button.addTarget(self, action: #selector(self.btnClick), for: .touchUpInside) @objc func btnClick() { NotificationCenter.default.post(name: NSNotification.Name.init(rawValue:self.accessibilityLabel!),对象:无)}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2016-01-12
  • 2012-09-23
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2015-12-31
相关资源
最近更新 更多