我试图将Obj-c中的以下代码转换为swift:
CustomButton.h
@property (nonatomic, copy) void (^defaultAction)();
CustomButton.m
- (void)executeTargetActionBlock {
if (self.defaultAction)
self.defaultAction();
}
- (void) initialize {
[self addTarget:self action:@selector(executeTargetActionBlock) forControlEvents:UIControlEventTouchUpInside];
}
这个initializeMethod在CustomButton的init方法中调用。
答案 0 :(得分:4)
class CustomButton: UIButton {
var defaultAction: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
self.addTarget(self, action: "executeTargetActionBlock", forControlEvents: UIControlEvents.TouchUpInside)
}
func executeTargetActionBlock() {
if let action = defaultAction {
action()
}
}
}