swift 按钮上的 IBAction 有两个 类

swift IBAction on button with two classes

我想知道我是否可以使用在另一个 class 中创建的按钮触发操作。

我解释一下:

我有两个 class 视图控制器和一个 class 用于创建视图。

在视图控制器中,我调用位于第二个 class 中的方法来创建自定义视图。然后我将自定义视图添加到主视图(参见下面的代码)。 自定义视图显示一个按钮,我不知道如何使用我的按钮,因为当我 运行 我的应用程序时找不到作为目标创建的方法。

代码viewController:

import UIKit

class FirstViewController: UIViewController {

    var popupViewBeforeOrderCoupon:UIView?

    override func viewDidLoad() {
        super.viewDidLoad()

        popupViewBeforeOrderCoupon = CustomView.createPopupViewWithList()
        self.view.addSubview(popupViewBeforeOrderCoupon!)        
    }

    func cancelView(sender: UIButton!) {
        var alertView = UIAlertView();
        alertView.addButtonWithTitle("OK");
        alertView.title = "Alert";
        alertView.message = "Button Pressed!!!";
        alertView.show();
    }

}

和第二个 class CustomView:

import Foundation
import UIKit

class CustomView {

    init () {

    }

    static func createPopupViewWithList() -> UIView? {
        var dynamicView = UIView(frame: CGRectMake(100, 200, 200, 100))
        dynamicView.backgroundColor = UIColor.grayColor()
        dynamicView.alpha = 1
        dynamicView.layer.cornerRadius = 5
        dynamicView.layer.borderWidth = 2

        let button = UIButton();
        button.setTitle("Add", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button.frame = CGRectMake(10, 10, 100, 50)
        dynamicView.addSubview(button)

        button.addTarget(self, action: "cancelView:", forControlEvents: .TouchUpInside)

        return dynamicView
    }

    func cancelView(sender: UIButton!) {
        var alertView = UIAlertView();
        alertView.addButtonWithTitle("OK");
        alertView.title = "Alert";
        alertView.message = "Button Pressed!!!";
        alertView.show();
    }
}

我希望在 customView 中创建的按钮在我按下时调用方法 cancelView,但我没能做到。

这是我得到的错误:

NSForwarding: warning: object 0x523c8 of class 'Myproject.CustomView' does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector +[Myproject.CustomView cancelView:]

我该怎么做?

您可以修改 createPopupViewWithList 以接受 UIViewController 的 1 个参数,然后将按钮的目标设置为它。

代码:

static func createPopupViewWithList(controller: UIViewController) -> UIView? {
    var dynamicView = UIView(frame: CGRectMake(100, 200, 200, 100))
    dynamicView.backgroundColor = UIColor.grayColor()
    dynamicView.alpha = 1
    dynamicView.layer.cornerRadius = 5
    dynamicView.layer.borderWidth = 2

    let button = UIButton();
    button.setTitle("Add", forState: .Normal)
    button.setTitleColor(UIColor.blueColor(), forState: .Normal)
    button.frame = CGRectMake(10, 10, 100, 50)
    dynamicView.addSubview(button)

    // set your controller here
    button.addTarget(controller, action: "cancelView:", forControlEvents: .TouchUpInside)

    return dynamicView
}

然后从 FirstViewController 调用您的函数:

popupViewBeforeOrderCoupon = CustomView.createPopupViewWithList(self)