代表没有在UIBarItem点击调用

时间:2016-09-14 07:13:32

标签: ios iphone swift delegates

委托方法不会被称为点击UIBarItem。我经历了很多建议,都和我写的一样。

我按照建议尝试,没有解决方案。给所有代表打电话的代表。我做了每一件事。

class ViewController: CommonClass,Mydelegate {

    var vc = CommonClass()

    override func viewDidLoad() {
        super.viewDidLoad()
        vc = CommonClass(nibName: "CommonClass", bundle: nil)
        initializeCartBarButton()
        vc.delegate = self
        print( (vc.delegate))
    }

    func testing() {
        print("hello")
    }
}

class CommonClass: UIViewController {

    var delegate:Mydelegate?

    func initializeCartBarButton() {
        let cartBarButton = UIBarButtonItem()
        cartBarButton.title = "cart"
        cartBarButton.target = self
        cartBarButton.action = Selector("goToCart")
        self.navigationItem.rightBarButtonItem = cartBarButton;

    }

    func goToCart() {
        print("hi")
        if self.delegate?.testing() != nil {
            self.delegate?.testing()

        }else {
            print(self.delegate)
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我看到的是:

  1. CommonClass继承UIViewController
  2. ViewController继承CommonClass
  3. 表示View Controller可以直接调用CommonClass方法。
  4. 您可以直接从goToCart()
  5. 调用ViewController方法

    因此,无需使用委托模式来调用CommonClass的方法。

答案 1 :(得分:0)

演示使用自定义委托的示例示例:

ViewController.swift

import UIKit


protocol Mydelegate
{
    func testing()
}

class ViewController: UIViewController {


    var delegate:Mydelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        goToCart()
    }

    func goToCart() {
        print("hi")
        if delegate?.testing() != nil {
            delegate?.testing()

        }else {
            print(delegate)
        }
    }
}

ViewController2.swift

import UIKit

class ViewController2: UIViewController, Mydelegate {


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }

    func testing() {
        print("hello")
    }

    @IBAction func goButtonAction(sender: AnyObject) {

        let vc: ViewController = storyboard?.instantiateViewControllerWithIdentifier("viewC") as! ViewController
        vc.delegate = self
        print( (vc.delegate))
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

enter image description here

ViewController的StoryBoardId是“viewC”