[英]Swift: Apply “addTarget” to a UIButton in a different class
I have a class called RecordViewFooter
where i create a UIButton
called microphoneButton
. 我有一类叫做
RecordViewFooter
在那里我创建UIButton
称为microphoneButton
。 I add as a subview
and it looks beautiful. 我添加为
subview
,它看起来很漂亮。
However, when this button is selected i need to add something as a subview
to my ViewController
. 但是,选择此按钮后,我需要向
ViewController
添加一些内容作为subview
。 So i did this in my ViewController
: 所以我在
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!)
}
I can not figure out why it won't call the function when the button is selected. 我不知道为什么当选择按钮时它不会调用该函数。 Any thoughts?
有什么想法吗?
Try this modified code: 尝试以下修改的代码:
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!)
}
You can solved that problem by implementing following solutions : 您可以通过实施以下解决方案来解决该问题:
First Prepare object of RecordViewFooter class. 首先准备RecordViewFooter类的对象。 like here i create object of RecordViewFooter() class.
像这里,我创建RecordViewFooter()类的对象。
var popViewObj = UINib(nibName: "RecordViewFooter", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! RecordViewFooter
now Write this code after subview done. 现在在完成子视图后编写此代码。
popViewObj.microphoneButton.addTarget(self, action: "microphoneButtonPressed:",forControlEvents: UIControlEvents.TouchUpInside)
Now Add Selected button Event in your code: 现在,在您的代码中添加所选按钮事件:
func microphoneButtonPressed(sender: UIButton) { print("microphone button pressed") // Do Whatever u want... }
it will work fine.. i hope u will done with this code. 它会正常工作..我希望你会用这段代码。
I got it to work. 我知道了。 I had to create an object from the class that i want to reference the global variable.
我必须从要引用全局变量的类中创建一个对象。 Then do this:
然后执行以下操作:
objectFromClass.globalVariable.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.