我在理解 addtarget 的工作原理时遇到了一些问题。我已经在下面的 swift 类中复制了我的问题。该按钮正确显示在屏幕上,但当我按下它时,调用的是 PopupMenuViewController.pressed
函数,而不是 handlerClass.pressed
函数。
为什么?
import Foundation
import UIKit
import CoreLocation
class PopupMenuViewController : UIViewController
{
class handlerClass
{
func pressed(sender: UIButton!) {
/// **IT SEEMS LIKE THE CALL FROM ADDTARGET SHOULD GO HERE...**
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
}
}
func pressed(sender: UIButton!) {
// **BUT INSTEAD IT ENDS UP HERE!!!!**
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
}
override func viewDidLoad()
{
super.viewDidLoad()
let hc = handlerClass() // make me a member variable to fix this problem
let button1 = UIButton()
button1.frame = CGRectMake(10, 400, 100, 50)
button1.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.9)
button1.layer.cornerRadius = 10.0
button1.setTitle("Button ", forState: UIControlState.Normal)
// ** THE OFFENDING ADD TARGE CALL **
button1.addTarget(hc, action: "pressed:", forControlEvents: .TouchUpInside)
self.view.addSubview(button1)
}
}
FIX:感谢 Carl 指出这一点。 let hc = handlerClass()
应该提升为成员变量
最佳答案
来自Apple docs :
The target object—that is, the object to which the action message is sent. If this is nil, the responder chain is searched for an object willing to respond to the action message.
但是你指定了目标对象,这是怎么回事?另一个有趣的引用:
When you call this method, target is not retained.
你在一个函数中创建了这个对象,只存储在那里,所以一旦 block 结束,保留计数结束为 0,变量现在为 nil。
为避免这种情况,您可以将其作为属性添加到函数之前,然后在函数中实例化。
关于ios - 包含类或父类响应addtarget函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34190045/