Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView in UIView Swift

I want to create UITableView inside UIView but it does not work.

Here is my code-

import UIKit
import SnapKit

class ReorderView: UIView, UITableViewDataSource, UITableViewDelegate {

    var tableView = UITableView()

    let screenHeight = UIScreen.mainScreen().bounds.height
    let screenWidth = UIScreen.mainScreen().bounds.width

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

        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

        setup()
    }

    func setup() {

        self.backgroundColor = UIColor.blackColor()

        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: screenWidth*0.5, height: screenHeight))
        tableView.layer.backgroundColor = UIColor.blackColor().CGColor
        self.addSubview(tableView)
    }


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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = "heyjkhl;jhgjlk/vjhgghg"
        return cell
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
like image 723
Arkalyk Akash Avatar asked Aug 06 '16 07:08

Arkalyk Akash


1 Answers

Change your init method and call setup() before setting delegate, because you are setting delegate and datasource before initalizing the UITableView.

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

    setup()
    tableView.delegate = self
    tableView.dataSource = self
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 
}
like image 164
Nirav D Avatar answered Oct 04 '22 06:10

Nirav D