无法在另一个类中设置UIButton目标?

时间:2017-04-15 22:15:46

标签: ios swift uibutton uikit

我正在尝试构建一个自定义控制器来管理一组UIButtons。

设置和放置按钮的ViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIButton()
    button1.setTitle("Button 1", for: UIControlState.normal)
    button1.setTitleColor(UIColor.blue, for: UIControlState.normal)
    button1.frame.origin.y = 120
    button1.sizeToFit()
    button1.isUserInteractionEnabled = true

    let button2 = UIButton()
    button2.setTitle("Button 2", for: UIControlState.normal)
    button2.setTitleColor(UIColor.blue, for: UIControlState.normal)
    button2.frame.origin.y = 160
    button2.sizeToFit()


    let button3 = UIButton()
    button3.setTitle("Button 3", for: UIControlState.normal)
    button3.setTitleColor(UIColor.blue, for: UIControlState.normal)
    button3.frame.origin.y = 190
    button3.sizeToFit()

    let controller = CustomButtonController(buttons: button1, button2, button3)

    self.view.addSubview(button1)
    self.view.addSubview(button2)
    self.view.addSubview(button3) }

CustomButtonController:

class CustomButtonController : NSObject {
    init(buttons: UIButton...) {
        super.init()
        for aButton in buttons {
            aButton.addTarget(self, action: #selector(pressed(_:)), for: UIControlEvents.touchUpInside)
        }
    }

    func pressed(_ sender: UIButton) {
        print("Press received in CustomButtonController")
        //Never gets called
    }
}

如果我在ViewController内部的按钮上使用addTarget方法,那么它可以正常工作。知道为什么我们不能像这样添加目标到传递的UIButton吗?感谢

1 个答案:

答案 0 :(得分:2)

您正在CustomButtonController中将viewDidLoad创建为本地常量。只要viewDidLoad返回,此对象就会被释放,因此不再处理按钮点击。

您需要声明一个实例属性来保存控制器实例:

var controller: CustomButtonController!

override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIButton()
    button1.setTitle("Button 1", for: UIControlState.normal)
    button1.setTitleColor(UIColor.blue, for: UIControlState.normal)
    button1.frame.origin.y = 120
    button1.sizeToFit()
    button1.isUserInteractionEnabled = true

    let button2 = UIButton()
    button2.setTitle("Button 2", for: UIControlState.normal)
    button2.setTitleColor(UIColor.blue, for: UIControlState.normal)
    button2.frame.origin.y = 160
    button2.sizeToFit()


    let button3 = UIButton()
    button3.setTitle("Button 3", for: UIControlState.normal)
    button3.setTitleColor(UIColor.blue, for: UIControlState.normal)
    button3.frame.origin.y = 190
    button3.sizeToFit()

    controller = CustomButtonController(buttons: button1, button2, button3)

    self.view.addSubview(button1)
    self.view.addSubview(button2)
    self.view.addSubview(button3) 
}