2017-10-18 77 views
1

加入到TextField通过延伸通过我扩展添加动作的按钮,其在迅速

代码是必须在文本框的右侧增加了一个按钮---

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 
     } 
    } 

按钮被显示像截图一样,但我很困惑如何将操作设置为该按钮。我不能将其设置在扩展文件,因为我有不同的来回文本框不同的动作......

enter image description here

+0

可能是此链接对你有帮助尝试[https://stackoverflow.com/questions/40467847/how-to-set-a-function-as-function-argument-in-swift-3](https: //stackoverflow.com/questions/40467847/how-to-set-a-function-as-function-argument-in-swift-3) – Zee

回答

0

您可以设置一个目标按钮,当被调用的行动,你应该张贴通知像这样:

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

然后在你的ViewController中,你可以添加一个观察者并实现不同的动作。 使用多个UITextFields可以将userData传递给Notification。

+0

谢谢...我也这么做。 button.addTarget(self,action:#selector(self.btnClick),for:.touchUpInside) @objc func btnClick() NotificationCenter.default.post(name:NSNotification.Name.init(rawValue:self.accessibilityLabel !),对象:零) } –