How to Programmatically Fake a Touch Event to a Uibutton

how to programmatically fake a touch event to a UIButton?

It turns out that

[buttonObj sendActionsForControlEvents:UIControlEventTouchUpInside];

got me exactly what I needed, in this case.

EDIT: Don't forget to do this in the main thread, to get results similar to a user-press.


For Swift 3:

buttonObj.sendActions(for: .touchUpInside)

programmatically tap UIButton swift

have you tried:

myAutomatedButton.sendActionsForControlEvents(.TouchUpInside)

This appears to be a previous question and a possible duplicate, but the post I found was: how to programmatically fake a touch event to a UIButton?

+1 for swift 3/4 below: @Eneko Alonso

How to get touch event for uibutton outside of another uiwindow

I found the answer here and here

I subclassed UIWindow and did an override to the hitTest inside of there.

class AnotherWindow: UIWindow {

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

for subview in subviews.reversed() {

let convertedPoint = subview.convert(point, from: self)

if let candidate = subview.hitTest(convertedPoint, with: event) {

return candidate
}
}

return self
}
}

Then inside the SecondWindow class I used my subclass instead:

// this was what I originally used
var secondWindow: UIWindow?

// **This is what I'm using now**
var secondWindow: AnotherWindow?

Swift: Custom UIButton Class in View Controller Touch Event Not Trigger?

You may need a closure not a computed property

lazy var customBtn: CustomButton = {
let frame = CGRect(x: 48.0, y: 177.0, width: 80.0, height: 40.0)
let custom = CustomButton(frame: frame, title: "Test",alignment: NSTextAlignment.right)
return custom
}()

Here inside MainViewController

customBtn.addTarget(self,
action: #selector(touchCancel),
for: .touchUpInside)

you add the target to a newly created instance not to the one you added as a subview and it's the main difference between your implementation ( computed property ) and closure



Related Topics



Leave a reply



Submit