how to programmatically fake a touch event to a UIButton?

后端 未结 8 1858
余生分开走
余生分开走 2020-11-29 15:48

I\'m writing some unit tests and, because of the nature of this particular app, it\'s important that I get as high up the UI chain as possible. So, what I\'d l

8条回答
  •  既然无缘
    2020-11-29 16:17

    It's handy for people who write Unit Tests without UI Tests ;-)

    Swift 5 way to solve it for UIBarButtonItem, which does not have sendAction method like UIButton etc.

    extension UIBarButtonItem {
        func sendAction() {
            guard let myTarget = target else { return }
            guard let myAction = action else { return }
            let control: UIControl = UIControl()
            control.sendAction(myAction, to: myTarget, for: nil)
        }
    }
    

    And now you can simply:

    let action = UIBarButtonItem(title: "title", style: .done, target: self, action: #selector(doSomething))
    action.sendAction()
    

提交回复
热议问题