【问题标题】:Delegate not called at UIBarItem tap在 UIBarItem 点击时未调用委托
【发布时间】:2017-01-21 21:49:48
【问题描述】:

委托方法不调用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)
        }
    }
}

【问题讨论】:

  • 触摸时是否打印出“hi”消息?
  • 是,但如果条件失败
  • 下一个打印是“nil”?
  • 您的 MyDelegate 看起来如何?
  • @ShadowOf 是的。自定义委托,只是打印你好(不打印)。

标签: ios iphone swift delegates


【解决方案1】:

我看到的是:

  1. CommonClass 继承 UIViewController
  2. ViewController 继承 CommonClass
  3. 意味着 View Controller 可以直接调用 CommonClass 方法。
  4. 你可以直接从ViewController调用goToCart()方法。

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

【讨论】:

  • 如果遗漏了有关您的应用程序工作逻辑的内容,请告诉我。
【解决方案2】:

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

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)
    }
}

ViewController 的 StoryBoardId 是“viewC”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2014-03-18
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多