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

标签 ios swift uitableview uiscrollview

我正在尝试创建一个由 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 类,它还实现了 UITableViewDataSource 和 UITableViewDelegate 以及需要启动 UITableView 的 2 个必需函数(cellForRowAtIndexPathnumberOfRowsInSection)

但是一旦我尝试通过取消注释

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

我的程序因 EXEC_BAD_ACCESS 而崩溃

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

最佳答案

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

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

你可能应该这样做:

@IBOutlet var foo: SomethingViewController! 位于顶部

然后使用self.foo = SomethingViewController()

关于iOS Swift 将 2 个或更多 UITableView 放入带有数据源和委托(delegate)的 UIScrollView 中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897615/

相关文章:

ios - 如何使用Daniel Chart将X值设置为条形图 View X轴?

ios - ios中如何解析多个json?

iphone - 将数据从 plist 加载到 UITableView

iOS - 如何设置 View 宽度等于 TableView 分隔符宽度

ios - 使用 git 子模块/cocoapods

ios - 如何在 SwiftUI 中与 GeometryReader 正确对齐

ios - 使用 Safariservices swift 如何围绕小黑框进行编码

swift - 如何在两个 View Controller 之间发送结构数组?

ios - segue时如何获取自定义单元格标签?

ios - 以编程方式创建和显示 UIBarButtonItem 的正确方法是什么?