繁体   English   中英

如何从子视图访问超级视图的视图控制器

[英]How to access a superview's view controller from a child view

我正在创建一个UIView ,里面有一个UITableView 我想将此UITableView委托和数据源设置为其超级视图的视图控制器。

代码:

import UIKit

class AllTasksView: UIView {

    let tableview = UITableView()

    override init(frame: CGRect) {
        super.init(frame: frame)

    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    }
     override func didMoveToSuperview() {
    tableview.delegate = "SUPERVIEW.ViewController"
    tableview.dataSource = "SUPERVIEW.ViewController"
}

可以这样做吗? 在哪里最好override UITableview方法? 我已经在我的UIViewController这样做了。

由于关注点分离,您无法从UIView访问UIViewController

或者,您可以使用委托来访问UIViewController

   class AllTasksView{
       weak var delegate: UITableViewDataSource & UITableviewDelegate?{
           didSet{
               tableView.delegate = newValue
               tableView.dataSource = newValue
           }
       }


   }

额外的

       class CustomVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
          //implement tableview methods here 


           func viewDidLoad(){
               super.viewDidLoad()

              let allTasksView = AllTasksView()
              view(addSubview: allTasksView)

              //add some positioning and size constraints here for allTasksView 

              allTasksView.delegate = self //this would call the didSet and would automatically setup the allTasksView.tableView's delegate and dataSource to this vc
           }
       }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM