【问题标题】:Get the correct Instance of ViewController for use with delegate function获取正确的 ViewController 实例以与委托函数一起使用
【发布时间】:2017-06-28 09:06:57
【问题描述】:

我正在尝试创建一个委托函数以在事件的不同视图控制器中重新加载集合视图。

为此我定义了一个协议,在类中设置委托,以及一个简单的委托函数。

protocol ReloadCollectionDelegate: class {
    func reloadCollectionViewFromDelegate()
}


class JourneyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITabBarControllerDelegate, UIScrollViewDelegate, ReloadCollectionDelegate {

    // delegate function from downloadCollectionController to relaod collection
    func reloadCollectionViewFromDelegate() {
        // simply call the reload function
        reloadCollection()
    }

在我的班级中将调用上述函数:

// define the delegate for use
weak var reloadJourneyDelegate: ReloadCollectionDelegate?

// reload the collection view in JourneyViewController
let JVC = self.viewController.storyboard!.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
self.reloadJourneyDelegate = JVC
self.reloadJourneyDelegate?.reloadCollectionViewFromDelegate() 

打印(JVC):

JourneyViewController: 0x7fc7f7c55bf0

print(self) - 来自 JourneyViewController (viewDidLoad):

JourneyViewController: 0x7fc7f7e2db10

所以我得到了同一个视图控制器的不同实例。

我如何定义它以便我拥有正确的实例并可以修改 UI?

谢谢

【问题讨论】:

  • 你在哪里调用viewDidLoad?
  • 在 JourneyViewController 类的 viewDidload() 中打印自己

标签: ios swift uiviewcontroller delegates protocols


【解决方案1】:

这对我有用,因为上面的答案没有:

let JCV = UIStoryboard(name: "Main", bundle: nil)
   .instantiateViewControllerWithIdentifier("JourneyViewController") as! JourneyViewController

导入部分是您必须在身份检查器中添加情节提要 ID。

【讨论】:

    【解决方案2】:

    这一行创建了一个JourneyViewController 的新实例

    self.viewController.storyboard!.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
    

    您必须有一种方法可以引用 JourneyViewController 的原始实例。要么有一个指向它的属性,要么两个视图控制器都在一个层次结构中,这样JourneyViewController 是另一个视图控制器的父级:

    class ViewControllerA: UIViewController {
        override viewDidLoad() {
            let button = UIButton(frame: CGRect(x: self.view.bounds.width/2, y: 400, width: 50, height: 50))
            button.backgroundColor = UIColor.black
            button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
            self.view.addSubview(button) 
        }
    
        func buttonPressed() {
            let journey = self.parent as! JourneyViewController
            journey.reloadCollection()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 1970-01-01
      • 2011-06-23
      • 2012-08-05
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 2013-11-26
      • 2010-10-09
      相关资源
      最近更新 更多