TableView滚动错误

问题描述:

我只是学习在Xcode上编写代码,目前正在学习如何使用TableView功能。我试图创建50个包含数字1到50的单元格,但是当我在iPhone 7上进行模拟时,我只能向下滚动到15.第15个单元格也不是全部单元格,并且当我水平旋转设备时我只能看到8个单元格。需要帮助的这个:(TableView滚动错误

这是我使用的代码:

import UIKit 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

     return 50 

    } 

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") 

     cell.textLabel?.text = String(indexPath.row + 1) 

     return cell 

    } 


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

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

这是位于屏幕底部的截图: Even cell 15 is not showing the full height

+0

这听起来像我的TableView控制没有约束设置,比如填满屏幕......我可以建议你添加一个你正在看到的屏幕截图,特别是当你处于底部时列表。 –

+1

你的故事板上的UItableview有什么约束? – Darshana

+0

可能存在约束问题,请使用XCode的3D层次结构调试工具来查看它,并且您需要使单元出列,使用单元的重用。 – Larme

改变你的代码如下::

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") 
     if (cell == nil) { 
     cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") 
     } 
     cell.textLabel?.text = "\(indexPath.row + 1)." 

     return cell 

    } 
+0

是行得通的吗? @Oswa Yuwawira – KKRocks

+0

哪些部分需要替换您刚给我的代码? 非常感谢您的帮助! –

+0

检查我的更新回答 – KKRocks

你需要更换:

let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")

通过:

var cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")

而且你应该添加在viewDidLoad

tableView.dataSource = self 
tableView.delegate = self
+0

我想我通过控制把我的viewtable拖到黄点事物两次,并检查dataSource和委托,在我的主要故事板上做了viewDidLoad事情。当我将“let”改为“var”时,Xcode给了我一个评论,说“变量”单元格从未发生过变化;考虑更改为“let”常量。尽管我可以忽略该评论并仍然运行代码。尽管如此,仍然不会让我滚动过去15。谢谢 –

+0

您是否尝试过创建具有独特文本的50个单元格?你可以滚动一下或是tableView完全修复? – Tibo

如果你把你的细胞在故事板,然后将这段代码

let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") 

此,

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! 

我希望这会起作用。

+0

这没有奏效。我觉得它更多的是与我设置的约束条件有关,或者与模拟器的设置有关(尽管我没有将任何设置更改为模拟器)。所以我总共有4个约束条件,我通过点击我的主要板上的“添加新约束”按钮上的红线并将距离最近的邻居设置为0 –