iOS Swift 将 2 个或更多 UITableView 放入具有数据源和委托的 UIScrollView 中时出现问题

iOS Swift Problems putting 2 or more UITableView in a UIScrollView with datasource and delegate

我正在尝试创建一个包含 2 个或更多 UITableView 的 UIScrollView,用户可以从左向右滑动以在 UITableView 之间切换

到目前为止我所做的是将 2 个 UITableView 放入 UIScrollView 中,如下所示:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var theScroll: UIScrollView!
    @IBOutlet var tableView1: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView1 = UITableView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
        self.tableView1.delegate = self
        self.tableView1.dataSource = self


        var foo = SomethingViewController()

        var tableView2:UITableView = UITableView(frame: CGRectMake(self.view.frame.width, 0, self.view.frame.width, self.view.frame.height))
//        tableView2.delegate = foo
//        tableView2.dataSource = foo

        self.theScroll.addSubview(tableView1)
        self.theScroll.addSubview(tableView2)

        self.theScroll.contentSize = CGSizeMake(self.view.frame.width * 2, 0)

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

        cell.textLabel?.text = "hello"
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

}

我也实现了你可能注意到的 SomeViewController class 它也实现了 UITableViewDataSource 和 UITableViewDelegate 以及需要启动 UITableView 的 2 个必需函数(cellForRowAtIndexPathnumberOfRowsInSection)

然而,一旦我尝试通过取消注释

将第二个表视图 (tableView2) 连接到实例化的 SomethingViewController
//        tableView2.delegate = foo
//        tableView2.dataSource = foo

我的程序崩溃 EXEC_BAD_ACCESS

我在这里做错了什么?如果还有其他建议,我愿意接受其他建议,谢谢!

首先,您可能应该在某处存储对第二个 tableView 的引用,而不仅仅是将其放入滚动视图中。但这不是你崩溃的原因。

其次,您崩溃的原因。您不存储对 'foo' 的引用,这意味着它将在 viewDidLoad 完成后被释放。

你可能应该这样做:

@IBOutlet var foo: SomethingViewController! 在顶部

然后使用self.foo = SomethingViewController()