AddTarget doesn't work for UIButton created in Swift

So, I created a UIButton using Swift and I animate it and it previews using the following code:

    override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.

      //create a UIView to contain buttons. Set background color to nil, so it transparent.
      var controlsView = UIView(frame: CGRect(x:0, y:0, width:400, height:400));
      controlsView.alpha = 1.0
      controlsView.backgroundColor = nil

      //create a button and add some attributes. Self explanatory
      var loginButton: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
      loginButton.frame = CGRectMake(20.0, 40.0, 200, 60)
      loginButton.alpha = 0.0
      loginButton.setTitle("Login", forState: .Normal)
      loginButton.titleColorForState(.Normal)
      loginButton.layer.cornerRadius = 20;
      loginButton.layer.borderWidth = 1.0
      loginButton.layer.borderColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [0.827, 0.325, 0.0, 1.0])
      loginButton.addTarget(self, action: "loginPressed:", forControlEvents: .TouchUpInside)

      //add the button to the view created to hold it
      controlsView.addSubview(loginButton)

      //now test blurring the background view. Create a UIVisualEffectView to create the blur effect. New in iOS7/8
    /*
      var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
      visualEffectView.frame = self.introImage.bounds
      self.introImage.addSubview(visualEffectView)
      visualEffectView.alpha = 0.0
    */

      //add the controls subview to the image view already here.
      self.introImage.addSubview(controlsView)

      //loginButton.addTarget(self, action: "loginButtonWasPressed:",forControlEvents:.TouchUpInside)


      UIView.animateWithDuration(0.7,
        animations: {
            loginButton.alpha = 1.0
            loginButton.frame = CGRect(x: 20.0, y: 100.0, width: 200, height: 60)
            //visualEffectView.alpha = 0.5
        },
        completion:nil)
    }

      

This works fine. Then I created a function to be called on the touchUpInside of the button that I created above:

    @IBAction func loginPressed(sender:UIButton){
      var alertView = UIAlertView();
      alertView.addButtonWithTitle("Ok");
      alertView.title = "title";
      alertView.message = "message";
      alertView.show();
    }

      

When I touch the button, the function does NOT start. Can anyone please help? I am testing this on a real device (iPhone 6 Plus / iOS 8.1.1

+3


source to share


1 answer


To add an action to a button, you need to use the following code

loginButton.addTarget(self,action:#selector(loginPressed),
forControlEvents:.TouchUpInside)

      



This code works for me. For more details you can follow this [ Attach parameter to action button.addTarget in Swift

Thank.

+1


source







All Articles