简体   繁体   中英

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

I am trying to create a UIScrollView which consist of 2 or more UITableViews and the user can swipe left to right to switch between UITableViews

What i have done so far is putting 2 UITableViews in a UIScrollView like this:

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
    }

}

I have also implemented as you may noticed the SomeViewController class which also implements the UITableViewDataSource and UITableViewDelegate with the 2 required function that needs to fire up a UITableView ( cellForRowAtIndexPath and numberOfRowsInSection )

however once i tried to connect the second tableview ( tableView2 ) to the instantiated SomethingViewController by uncommenting the

//        tableView2.delegate = foo
//        tableView2.dataSource = foo

my program crashes with EXEC_BAD_ACCESS

what am i doing wrong here? if there is another I am open to other suggestions, thanks!

First of all, you should probably store a reference to the second tableView somewhere and not just put it into your scrollview. But this is not the reason for your crash.

Secondly:, the reason for your crash. You don't store a reference to 'foo', which means it will be deallocated after the viewDidLoad finishes.

You should probably do something like this:

@IBOutlet var foo: SomethingViewController! at the top

and then use self.foo = SomethingViewController()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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