【发布时间】:2018-02-25 05:55:53
【问题描述】:
我在一个 ScrollView 中有 2 个 tableView:
- tableViews 无法滚动,将显示所有行
- 两个 tableView 都有带有按钮的自定义单元格
- 从 TableView2 中按下一个按钮将向 TableView1 添加一行
问题:
1) 它最初可以工作,按下 TableView2 中的按钮将执行服务调用,然后将单元格添加到 TableView1。
2) 但是我注意到,一旦 TableView1 展开以占据屏幕的高度并且我向下滚动以访问 TableView2,按下 TableView2 上的按钮不再注册任何内容。它根本不会触发动作。这是我认为可能是问题但不确定的想法。
一些代码
extension MyFeedViewController: UITableViewDelegate,UITableViewDataSource{
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if tableView == self.tableView1
{
return tableView1Array.count
}
else
{
return tableView2Array.count
}
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if tableView == self.tableView1
{
let cell:TableView1Cell = self.tableView1.dequeueReusableCell(withIdentifier: "TableView1Cell", for: indexPath) as! cell:TableView1Cell
cell.updateCell(withObject:)
cell.delegate = self
return cell
}
else
{
let cell:TableView2Cell = self.tableView2.dequeueReusableCell(withIdentifier: "TableView2Cell", for: indexPath) as! TableView2Cell
cell.updateCell(withObject:withType)
cell.delegate = self
return cell
}
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
if tableView == self.tableView1
{
return CGFloat(80)
}
else
{
return CGFloat(60)
}
}
}
从服务器获得成功响应后,我会像这样触发我的滚动视图的重新计算:
override func viewDidLayoutSubviews()
{
refreshTableHeights()
}
//Called when a success server call is made
func refreshTableHeights()
{
//Update table height
if tableView1Array.count > 0
{
tableView1HeightConstraint.constant = CGFloat(tableView1Array.count * 80)
}
else
{
tableView1HeightConstraint.constant = CGFloat(80)
}
if tableView2Array.count > 0
{
tableView2HeightConstraint.constant = CGFloat(tableView2Array.count * 60)
}
else
{
tableView2HeightConstraint.constant = CGFloat(60)
}
view.layoutIfNeeded()
//Set content view
let extraSpace = CGFloat(200)
contentView.frame.size.height = tableView1.frame.size.height + tableView2.frame.size.height + extraSpace
scrollView.contentSize = contentView.frame.size
}
其他一些注意事项:
- 表格高度在我的 IB 中是固定的,因此我通过代码手动更改 tableViews 的高度约束。
-
带有 IBAction 的按钮在其自定义单元格中定义。从 TableView 2 中按下一个按钮将触发一个委托调用回我的 VC 以进行服务调用。
如果有人能在我迷路时指出正确的方向,那就太好了。谢谢!
【问题讨论】:
-
您能否更具体地说明您为什么要手动更新表格视图高度?看看您的自定义单元格类的样子也会很有帮助
-
通过在模拟器中运行来捕获您的界面。查看按钮是否在其父视图的框架中。如果视图在其父视图之外,则视图上的触摸操作不会响应。
-
@Naresh 谢谢你这是我的问题。我的 contentview 有一个约束,它在滚动视图滚动时重置 contentview 高度。
-
不客气,我写它作为答案。
标签: swift xcode button tableview scrollview