ios - 包含类或父类响应addtarget函数

标签 ios swift

我在理解 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/

相关文章:

iphone - 从 URL 读取文本文件会返回错误的字符串

swift ,macOS : Open terminal window at the location

ios - 如何使用 swift 在 iOS 中生成证书(.crt 文件)或在哪里可以找到相关文档

swift - 事件指示器未正确显示

iPhone - 应用程序在后台运行时更改应用程序设置

ios - 栏按钮在运行时未显示在导航栏上

ios - 设置段颜色的tintColor时如何停止导航栏TintColor的变化?

swift - 在 Firebase 数据库中按用户名搜索用户?

objective-c - 如何在从 XIB 实例化的自定义 View 上设置属性

IOS 对象字段意外设置为 nil