【问题标题】:Is it possible to set a block as a target on a UIButton?是否可以将块设置为 UIButton 上的目标?
【发布时间】:2011-12-03 01:47:07
【问题描述】:

我需要在按下按钮时向方法发送额外的参数,但找不到让 addTarget 发送选择器来执行此操作的方法。

无论如何我宁愿使用块,但是有没有一种方法可以在运行时将块附加到 UIButton?

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    是的,您可以使用 BlocksKit 库轻松完成:

    #import <BlocksKit/UIControl+BlocksKit.h>
    
    [someButton addEventHandler:^(id sender) {
        // some action here
    } forControlEvents:(UIControlEventTouchUpInside)];
    

    或使用 RxSwift button.rx.tap observable。

    【讨论】:

    • 很棒的图书馆!谢谢。
    【解决方案2】:

    默认情况下不是。不过,您可以继承 UIButton 来实现这一点。有人做到了here

    【讨论】:

    • 该答案中的一个 cmets 有充分理由说明为什么不进行子类化,只是我的情况是 OP 没有读过答案
    【解决方案3】:

    也许晚点参加聚会,但您可以使用我几周前制作的简单扩展来实现您的目标。你可以得到它here

    并按如下方式使用:

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        override func viewDidAppear(animated: Bool) {
            let aButton = UIButton(type: .Custom)
            aButton.frame = CGRectMake(100, 100, 100, 80)
            aButton.backgroundColor = UIColor.greenColor()
            aButton.handleControlEvent(.TouchUpInside) { () -> Void in
                NSLog("ich")
            }
            self.view.addSubview(aButton)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-14
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多