cellForRow未被调用但正在调用numberOfSection和numberOfRowsInSection

问题描述 投票:2回答:4

我的代码:

//Adding Destination VC as subview in my current view's view container
let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "DestinationViewControllerID")
         containerView.addSubview(viewController.view)
        viewController.didMove(toParentViewController: self)

//Now implementing Table view in the destination vc

class DestinationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

 var tableView = UITableView()
    var tableData = ["Beach", "Clubs", "Chill", "Dance"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let screenBounds = UIScreen.main.bounds
        let rect = CGRect(x: 0, y: 0, width: screenBounds.width, height: screenBounds.height)
        tableView = UITableView(frame: rect, style: UITableViewStyle.plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.blue

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "my")

        view.addSubview(tableView)

        tableView.reloadData()
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "my", for: indexPath)
        cell.textLabel?.text = "This is row \(tableData[indexPath.row])"

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4//tableData.count
    }
}

如果我将目标viewController设置为来自storyboard的初始vc,那么一切正常。但是如果在容器视图中添加subview,则不会调用cellForRowAt方法,而是调用numberOfSection和numberOfRowsInSection。

有没有人有任何解决方案?

ios swift uitableview uikit tableview
4个回答
3
投票

在子视图之前添加self.addChildViewController(viewController)

     let storyboard = UIStoryboard(name: "Main", bundle: nil)
     let viewController = storyboard.instantiateViewController(withIdentifier: "DestinationViewControllerID")

     self.addChildViewController(viewController)
     containerView.addSubview(viewController.view)
     viewController.didMove(toParentViewController: self)

0
投票

确保在UITableView上设置约束。如果是这样,请尝试手动设置UITableViewCell的高度。


0
投票

重新检查是注册的reusableidentifier

tableView.dequeueReusableCell(withIdentifier:“my”,for:indexPath)


0
投票

首先,您需要在故事板中有一个tableview。创建tableView后,您可以通过以下方式以编程方式进行子视图:

self.view.addSubview(tableView)

或者在故事板中添加tableView并创建一个这样的IBOutlet:

@IBOutlet weak var tableView: UITableView!

其次,你没有初始化你的单元格,你只是将先前创建的单元格出列(在你的情况下从未创建过)。你的代码应该是这样的:

var cell = tableView.dequeueReusableCell(withIdentifier: "my", for: indexPath) as UITableViewCell?
if cell == nil { 
    cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "my")
   }
© www.soinside.com 2019 - 2024. All rights reserved.