UIButton addTarget选择器不起作用 [英] UIButton addTarget Selector is not working

查看:46
本文介绍了UIButton addTarget选择器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SquareBox.swift

SquareBox.swift

class SquareBox {
  func createBoxes() {
    for _ in 0..<xy {
            let button = UIButton()

            button.backgroundColor = .white
            button.setTitleColor(UIColor.black, for: .normal)
            button.layer.borderWidth = 0.5
            button.layer.borderColor = UIColor.black.cgColor
            stack.addArrangedSubview(button)
            button.addTarget(self, action: #selector(click(sender:)) , for: .touchUpInside)
    }
  }

  @objc func click(sender : UIButton) {
    print("Click")
  }
}

ViewController.swift

ViewController.swift

class GameViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let boxRow = SquareBox() 
        boxRow.createBoxes()
    }
}

我也尝试了@IBAction而不是@objc,它不起作用,但是如果我在ViewController.swift中使用"click"函数创建了该对象,则它正在起作用,但是我需要在此类中使用此函数

Also I've tried @IBAction instead of @objc, it doesn't work, but if I use "click" function in ViewController.swift that I created this object, it's working but I need this function inside of this class.

推荐答案

现在您已经在问题中发布了相关信息,问题很明显.您遇到内存管理问题.

Now that you have posted relevant information in your question, the problem is quite clear. You have a memory management issue.

在GameViewController的 viewDidLoad 中,创建 SquareBox 的本地实例.此本地实例在 viewDidLoad 的末尾超出范围.由于没有对该实例的其他引用,因此它会在 viewDidLoad 的末尾释放.

In your GameViewController's viewDidLoad you create a local instance of SquareBox. This local instance goes out of scope at the end of viewDidLoad. Since there is no other reference to this instance, it gets deallocated at the end of viewDidLoad.

由于已经释放了 SquareBox 的实例,因此它不能用作按钮的目标.而且您的 click 方法将永远不会被调用.

Since the instance of SquareBox has been deallocated, it is not around to act as the button's target. And your click method is never called.

解决方案是在视图控制器中保留引用:

The solution is to keep a reference in your view controller:

class GameViewController: UIViewController {
    let boxRow = SquareBox() 

    override func viewDidLoad() {
        super.viewDidLoad()
        boxRow.createBoxes()
    }
}

这篇关于UIButton addTarget选择器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆