簡體   English   中英

addTarget 不適用於在 Swift 中創建的 UIButton

[英]addTarget not working for UIButton created in Swift

因此,我使用 Swift 創建了一個 UIButton,並使用以下代碼對其進行了動畫處理,並且它是超級視圖:

    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's 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)
    }

這工作正常。 然后我創建了一個函數,它應該在我上面創建的按鈕的 touchUpInside 上調用:

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

當我觸摸按鈕時,該功能不會觸發。 任何人都可以幫忙嗎? 我正在實際設備上對此進行測試(iPhone 6 Plus/iOS 8.1.1

要將動作添加到按鈕,您需要使用以下代碼

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

這段代碼對我來說很好用。 有關更多詳細信息,您可以按照此 [ 將參數附加到 Swift 中的 button.addTarget 操作

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM