ios - UIView Swift 中的 UITableView

标签 ios swift uitableview

我想在 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")
    }

}

最佳答案

在设置委托(delegate)之前更改您的init 方法并调用setup(),因为您正在设置delegatedatasource 在初始化 UITableView 之前。

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

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

关于ios - UIView Swift 中的 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38801649/

相关文章:

iOS 9 Spritekit 双击在 iPhone 6S 上不起作用

ios - 当前上下文中的自定义转换

swift - 如何使用 SwiftUI 以编程方式转换 View ?

java - 在 iOS7 中编码 UIImage 并在 Java 中解码(Base64)

ios - 在使用 Cocoapods 的项目中执行单元测试时出现 "Class X is implemented in both"

ios - UITableViewAutomaticDimension 的约束错误

ios - 如何将 .sks 文件添加到现有 Swift/Sprite-Kit 项目?

ios - 异步获取JSON后如何重新加载tableView? objective-c

ios - UISearchBar 在向下滚动之前不可见

ios - UITableView 动画无法正常工作