UITableView在UIView中的Swift实现

11
我想在UIView中创建UITableView,但不起作用。
这是我的代码 -
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")
    }

}

这是一个UIView,所以我猜只有self.addSubview会起作用。 - Arkalyk Akash
实际上,tableView是显示出来了,但是没有文本。 - Arkalyk Akash
不需要重新加载或更改设置位置。 - Bhavin Bhadani
1个回答

16

在设置delegatedatasource之前,请更改您的init方法并在调用setup()方法后进行,因为您是在初始化UITableView之前设置它们的。

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

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

好的,我现在会尝试。 - Arkalyk Akash
好的,它说要等6分钟。 - Arkalyk Akash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接