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

前端 未结 8 1820
滥情空心
滥情空心 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:02

    This is not necessarily a "hooking," but you can effectively achieve this behavior by subclassing UIButton:

    class ActionButton: UIButton {
        var touchDown: ((button: UIButton) -> ())?
        var touchExit: ((button: UIButton) -> ())?
        var touchUp: ((button: UIButton) -> ())?
    
        required init?(coder aDecoder: NSCoder) { fatalError("init(coder:)") }
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupButton()
        }
    
        func setupButton() {
            //this is my most common setup, but you can customize to your liking
            addTarget(self, action: #selector(touchDown(_:)), forControlEvents: [.TouchDown, .TouchDragEnter])
            addTarget(self, action: #selector(touchExit(_:)), forControlEvents: [.TouchCancel, .TouchDragExit])
            addTarget(self, action: #selector(touchUp(_:)), forControlEvents: [.TouchUpInside])
        }
    
        //actions
        func touchDown(sender: UIButton) {
            touchDown?(button: sender)
        }
    
        func touchExit(sender: UIButton) {
            touchExit?(button: sender)
        }
    
        func touchUp(sender: UIButton) {
            touchUp?(button: sender)
        }
    }
    

    Use:

    let button = ActionButton(frame: buttonRect)
    button.touchDown = { button in
        print("Touch Down")
    }
    button.touchExit = { button in
        print("Touch Exit")
    }
    button.touchUp = { button in
        print("Touch Up")
    }
    

提交回复
热议问题