Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton in Swift is not registering touches

I'm trying to create a UIButton using Swift. It compiles fine and I can see my button in the simulator, but when I click it, nothing happens. This is the code I am using:

let settings = UIButton() settings.addTarget(self, action: "touchedSet:", forControlEvents: UIControlEvents.TouchUpInside) settings.setTitle("Settings", forState: .Normal) settings.frame = CGRectMake(0, 530, 150, 50) scrollView.addSubview(settings) 

In the same class, here is the function 'touchedSet':

func touchedSet(sender: UIButton!) {     println("You tapped the button") } 

I'm using the simulator as I don't have an iOS 8.0 device, could that be the problem?

Thanks!

like image 575
Phillip Avatar asked Jun 04 '14 12:06

Phillip


People also ask

How can I check if UIButton is pressed?

If you want to check If UIButton is Pressed or not, You should handle TouchDown Handler and change button's state to pressed in touchDown hadnler. You can track ToucUpInside method to Change state of button to Not-pressed again.

What is a UIButton?

A control that executes your custom code in response to user interactions.


1 Answers

I see it is an old question but I just faced very similar problem yesterday. My buttons were highlighted on touch but not firing the action.

I have two view controllers. One view covers the others view and button is on the top view.

eg.

  • Rootviewcontroller has back view

  • Topviewcontroller has top view

The button on top view does not call the action if I don't add the topviewcontroler as childviewcontroller of the rootviewcontroller. After adding the topviewcontroller as childviewcontroller it started to working.

So in short: just try to add the view controller of buttons superview as childviewcontroller to the parent views viewcontroller with the following method

func addChildViewController(_ childController: UIViewController) 
like image 81
Mert Avatar answered Sep 18 '22 03:09

Mert