如何禁用tableView的滚动?

6

当我在一个视图控制器中添加默认的UITableView时,它会滚动,但我想让它静态。这可行吗?

以下是我的代码:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
   return names.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableview.dequeueReusableCellWithIdentifier("cell") as! TableViewCell
    cell.username.text = names[indexPath.row]
    return cell
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    return 50.0
}

1
你能解释一下“行移动”是什么意思吗? - Shubhank
你想要禁用tableView的滚动吗? - Umair Afzal
你想让表格视图中的某些行保持固定,而让其余行移动。 - Supratik Majumdar
yaaa @ supratik majumdar - Bansal
1
我不明白。在上面的评论中,您说您想禁用滚动。现在您又说您只想对某些单元格进行相同的操作。 - Supratik Majumdar
嗯,我想在表格视图中仅禁用滚动。 - Bansal
4个回答

14

Swift 3,4和5:

tableView.isScrollEnabled = false

6

在Interface Builder中禁用滚动。

选择表格视图和属性检查器⌥⌘4

然后取消选中启用滚动

enter image description here


3

选项1

尝试在 viewDidLoad() 中仅使用此行代码:

self.tableView.scrollEnabled = tableView.contentSize.height > tableView.frame.height;

这是缩写的方式:
if tableView.contentSize.height > tableView.frame.height {
    self.tableView.scrollEnabled = true;
}
else {
    self.tableView.scrollEnabled = false;
}

解释: 如果行数太多,需要的空间超过了tableview的大小,则表格将是可滚动的,否则不会。这就是为什么在代码中要将内容大小与窗口大小进行比较。

选项2:

如果你想要在所有情况下都禁用滚动,也可以在 viewDidLoad() 中添加以下内容:

self.tableView.scrollEnabled = false;

注意: 如果您为tableView指定了特殊名称,请在我分享的代码中用您的tableView名称替换它。


0

当内容大小适合于表视图的大小时,UITableView的滚动将被禁用

 if (tableView.contentSize.height < tableView.frame.size.height) {

   tableView.scrollEnabled = false
 }
else {

   tableView.scrollEnabled = true
 }

如果您想无论内容大小都禁用滚动:

tableView.scrollEnabled = false

更改 UITableView 的分隔线颜色(根据评论请求):

tableView.separatorColor = UIColor(red:0.16, green:0.17, blue:0.20, alpha:1.00)

这段代码出现了错误,您能详细解释一下吗? - Bansal
命名出现了错误,应该是 tableView,Edit 修改的。 - Supratik Majumdar
这段代码不会影响表格视图的用户界面,也不能禁用滚动。 - Bansal
还有一件事我想问,我们能否更改Swift中默认的tableview线条颜色? - Bansal

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