繁体   English   中英

Swift:将“ addTarget”应用于另一个类中的UIButton

[英]Swift: Apply “addTarget” to a UIButton in a different class

我有一类叫做RecordViewFooter在那里我创建UIButton称为microphoneButton 我添加为subview ,它看起来很漂亮。

但是,选择此按钮后,我需要向ViewController添加一些内容作为subview 所以我在ViewController做到了这一点:

    RecordViewFooter().microphoneButton.addTarget(self, action: "microphoneButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
    }
    func microphoneButtonPressed(){
    print("microphone button pressed")
    volumeAdjuster = VolumeAdjusterView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
    self.view.addSubview(volumeAdjuster!)
}

我不知道为什么当选择按钮时它不会调用该函数。 有什么想法吗?

尝试以下修改的代码:

RecordViewFooter().microphoneButton.addTarget(self, action: "microphoneButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

func microphoneButtonPressed(button:UIButton){
    print("microphone button pressed")
    volumeAdjuster = VolumeAdjusterView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
    self.view.addSubview(volumeAdjuster!)
}

您可以通过实施以下解决方案来解决该问题:

  1. 首先准备RecordViewFooter类的对象。 像这里,我创建RecordViewFooter()类的对象。

     var popViewObj = UINib(nibName: "RecordViewFooter", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! RecordViewFooter 
  2. 现在在完成子视图后编写此代码。

     popViewObj.microphoneButton.addTarget(self, action: "microphoneButtonPressed:",forControlEvents: UIControlEvents.TouchUpInside) 
  3. 现在,在您的代码中添加所选按钮事件:

     func microphoneButtonPressed(sender: UIButton) { print("microphone button pressed") // Do Whatever u want... } 
  4. 它会正常工作..我希望你会用这段代码。

我知道了。 我必须从要引用全局变量的类中创建一个对象。 然后执行以下操作:

    objectFromClass.globalVariable.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM