Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何访问superview';从子视图创建视图控制器_Ios_Swift_Iphone_Xcode - Fatal编程技术网

Ios 如何访问superview';从子视图创建视图控制器

Ios 如何访问superview';从子视图创建视图控制器,ios,swift,iphone,xcode,Ios,Swift,Iphone,Xcode,我正在创建一个UIView,其中将包含一个UITableView。我想将此UITableView委托和数据源设置为其superview的视图控制器 代码: import UIKit class AllTasksView: UIView { let tableview = UITableView() override init(frame: CGRect) { super.init(frame: frame) } required ini

我正在创建一个
UIView
,其中将包含一个
UITableView
。我想将此
UITableView
委托和数据源设置为其superview的视图控制器

代码:

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

可以这样做吗?在哪里最好覆盖
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
           }
       }

谢谢你的回复约书亚。你能进一步解释这个过程是如何工作的吗?我应该在newValue中添加什么。newValue是didSet中的一个特殊常量。在本例中,它将是CustomVcallTasksView.delegate=self的值,这不起作用,因为allTasksView没有名为delegate的成员。你是说allTasksView.table.delegate=self吗?不,我的意思是
allTasksView.delegate=self
。请参阅初始代码段,将
委托
属性添加到所有TasksView实例