【问题标题】:UIButton in Swift 2.2. How to add different target?Swift 2.2 中的 UIButton。如何添加不同的目标?
【发布时间】:2016-10-10 01:12:18
【问题描述】:

我在代码中创建了按钮。

        let item = UIButton()
        item.setImage(UIImage(named: "Menu"), forState: .Normal)
        view.addSubview(item)

如何从其他 VC 添加目标?

我尝试了很多东西,但它没有编译。

OtherClass 中的方法 menuButtonAction()

错误:

        item.addTarget(otherClassVar, action: #selector(OtherClass.menuButtonAction), forControlEvents: .TouchUpInside)
        item.addTarget(otherClassVar, action: #selector(OtherClass.menuButtonAction(_:)), forControlEvents: .TouchUpInside)

该方法立即调用选择器:

        item.addTarget(otherClassVar, action: Selector(OtherClass.menuButtonAction()), forControlEvents: .TouchUpInside)  

【问题讨论】:

    标签: ios swift uiview uibutton swift2


    【解决方案1】:

    SWIFT 2.2 或更新版本:

    yourButton.addTarget(self, action: #selector(TheClassName.runThis(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    

    我想很明显,您要运行的函数必须在您要运行它的类中实现。希望已经足够清晰了。

    func runThis(sender: AnyObject) {
           // ...
        }
    

    【讨论】:

      【解决方案2】:

      您正在尝试将menuButtonAction 设置为static/class 选择器,但实际上我认为它是实例方法,因为它没有被static/class 关键字标记

      试试这个:

      item.addTarget(otherClassVar, action: #selector(otherClassVar.menuButtonAction), forControlEvents: .TouchUpInside)
      

      【讨论】:

      • 我要插入@objc
      • @IgorBizi 如果你的otherClassVarOtherClass 类型,正确初始化并且OtherClassfunc menuButtonAction(){} 方法,那么我的代码必须工作。
      • @IgorBizi 您也应该在本网站提问时提供更多信息。成员不应猜测您在答案中的声明。
      【解决方案3】:

      希望对你有所帮助.....

      let button   = UIButton(type: UIButtonType.RoundedRect) as UIButton
          button.frame = CGRectMake(20, 20, 100, 150)
          button.backgroundColor = UIColor(red:125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0)
          button.setTitle("Test Button", forState: UIControlState.Normal)//Highlighted here you can change state....
          button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
          self.view.addSubview(button)
      

      然后调用函数....

      func buttonAction(sender:UIButton!)
      
      {
             print("welcome to swift 2.2")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-22
        • 2020-08-14
        • 2016-09-19
        • 1970-01-01
        • 1970-01-01
        • 2018-03-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多