在Swift中向customButton添加闭包

时间:2016-01-08 21:02:07

标签: ios objective-c swift

我试图将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方法中调用。

1 个答案:

答案 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()
        }
    }
}