【发布时间】:2011-12-03 01:47:07
【问题描述】:
我需要在按下按钮时向方法发送额外的参数,但找不到让 addTarget 发送选择器来执行此操作的方法。
无论如何我宁愿使用块,但是有没有一种方法可以在运行时将块附加到 UIButton?
【问题讨论】:
标签: iphone objective-c
我需要在按下按钮时向方法发送额外的参数,但找不到让 addTarget 发送选择器来执行此操作的方法。
无论如何我宁愿使用块,但是有没有一种方法可以在运行时将块附加到 UIButton?
【问题讨论】:
标签: iphone objective-c
是的,您可以使用 BlocksKit 库轻松完成:
#import <BlocksKit/UIControl+BlocksKit.h>
[someButton addEventHandler:^(id sender) {
// some action here
} forControlEvents:(UIControlEventTouchUpInside)];
或使用 RxSwift button.rx.tap observable。
【讨论】:
默认情况下不是。不过,您可以继承 UIButton 来实现这一点。有人做到了here。
【讨论】:
也许晚点参加聚会,但您可以使用我几周前制作的简单扩展来实现您的目标。你可以得到它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)
}
}
【讨论】: