【问题标题】:UIScrollView not scrolling with UITableViewUIScrollView 不与 UITableView 一起滚动
【发布时间】:2020-11-05 12:58:17
【问题描述】:

我正在尝试实现一个包含文本字段、按钮和表格视图的滚动视图。我完全迷失了试图让东西滚动,我尝试改变 UITableView 的高度但没有奏效,我尝试调整内容视图和滚动视图的高度,但这也没有奏效。当另一个tableViewCell添加到tableView时,如何让scrollview滚动并调整大小?

override func viewDidLayoutSubviews() {
        
        tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: CGFloat(tableView.numberOfRows(inSection: 0) * 120))
        tableView.reloadData()

    }


@IBAction func addExercisePressed(_ sender: Any) {
    test.append("nice")
    tableView.reloadData()
    
    tableView.frame = CGRect(x: tableView.frame.origin.x,y: tableView.frame.origin.y ,width: self.view.frame.size.width, height: CGFloat(test.count * 120))
    scrollView.frame.size = CGSize(width: self.view.frame.size.width, height: tableView.frame.size.height)
    
 
}

【问题讨论】:

  • 为什么在滚动视图中使用表格视图?您可以使用单个 tableview 来实现相同的布局,而不会出现您提到的任何问题
  • 怎么样,我想让按钮随着视图滚动,在tableView中可以吗?
  • 使用表头视图
  • 非常感谢

标签: ios swift uitableview uiscrollview scrollview


【解决方案1】:

请不要在scrollView中使用tableView,tableView是scrollView的子类,也就是说tableView已经有了滚动功能

你要设置的答案

tableHeight.constant = tableView.contentSize.height

它将使回收/出列单元格功能无用,因为 tableView 将立即显示所有单元格,tableview 将为 tableview 视口中显示的所有索引调用 cellForRowAt

UITableview inside Scrollview call cellforrow too many times

这里为什么我们使用dequeueReusableCellWithIdentifier

据我所知,你想要这样的权利

您可以查看repo 我如何只使用 一个 tableview 来实现这一点

请注意tableHeaderView是可滚动的,sectionHeaderView是粘性的

【讨论】:

  • tableHeight.constant = tableView.contentSize.height 仅在添加另一个单元格时调用,在 CellForRow 中不调用
  • 它会使 cellForRow 调用 tableView 中的每个单元格,并使 dequeueCell 无法按预期工作
  • 你可以看这个关于tableView回收单元格youtube.com/watch?v=z2y7oljRacg的解释
  • @Noah Iarrobino 尝试显示非常大量的单元格(例如:100000000),您会看到问题
  • @NoahIarrobino 它会让你的应用程序使用更多内存,并且在某些情况下可能会导致 UI/UX 故障,这个数字只是为了一个简单的例子,但如果你不关心这个,那就好了给你。甚至 Apple 也说“您不应该在 UIScrollView 对象中嵌入 UIWebView 或 UITableView 对象。如果这样做,可能会导致意外行为,因为这两个对象的触摸事件可能会混淆并错误处理。”
【解决方案2】:

我只需要为 TableView 设置一个高度约束并通过 IBOutlet 连接它,然后在需要重新加载表数据的地方使用这行代码

tableHeight.constant = tableView.contentSize.height

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多