Hooking up UIButton to closure? (Swift, target-action)

前端 未结 8 1789
滥情空心
滥情空心 2020-12-13 02:51

I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, ac

8条回答
  •  囚心锁ツ
    2020-12-13 03:11

    This is easily solved using RxSwift

    import RxSwift
    import RxCocoa
    
    ...
    
    @IBOutlet weak var button:UIButton!
    
    ...
    
    let taps = button.rx.tap.asDriver() 
    
    taps.drive(onNext: {
        // handle tap
    })
    

    Edit:

    I wanted to acknowledge that RxSwift/RxCocoa is a pretty heavy-weight dependency to add to a project just to solve this one requirement. There may be lighter-weight solutions available or just stick with target/action pattern.

    In any case, if the idea of a general purpose declarative approach to handling application and user events appeals to you, definitely give RxSwift a look. It's the bomb.

提交回复
热议问题