在我的应用程序中,我有两个并排的tableViews。当用户滚动时,我希望第二个tableView同时滚动,以便它看起来几乎像一个带有两个不同列的表格。我有点迷茫如何处理这个问题,请问有什么建议吗?
谢谢, Greg
谢谢, Greg
UITableView非常方便地是UIScrollView的子类。存在一个UIScrollViewDelegate代理,其中有这个方法:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
如果你实现了这个方法,你可以获取到scrollView
参数的contentOffset
属性。然后,你应该使用它。- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated
并设置新的内容偏移量。因此,可以像这样实现:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
UIScrollView *otherScrollView = (scrollView == self.tableView1) ? self.tableView2 : self.tableView1;
[otherScrollView setContentOffset:[scrollView contentOffset] animated:NO];
}
如果你愿意,可以将其转换为UITableView,但没有特别的原因需要这样做。
UIScrollViewDelegate
- 假设你有两个滚动视图,A和B。scrollViewDidScroll
委托方法来获取偏移量,然后在同一方法中调用setContentOffset
在滚动视图B上,将从委托获取的值传递进去。此外,用户滚动的表格视图不应在scrollViewDidScroll中发送setContentOffset:消息,否则会使应用程序进入无限循环。因此,需要实现其他UIScrollViewDelegate方法来解决该问题:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
beingScrolled_ = nil;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
if(beingScrolled_ == nil)
beingScrolled_ = scrollView;
}
并根据Inspire48的版本修改scrollViewDidScroll:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
UIScrollView *otherScrollView = (scrollView == self.tableView1) ? self.tableView2 : self.tableView1;
if(otherScrollView != beingScrolled)
{
[otherScrollView setContentOffset:[scrollView contentOffset] animated:NO];
}
}
在这里,beingScrolled_是一个类型为UIScrollView的实例变量。
UITableView是UIScrollView的子类。Swift解决方案:
extension yourViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let otherScrollView = (scrollView == tableViewLeft) ? tableViewRight : tableViewLeft
otherScrollView?.setContentOffset(scrollView.contentOffset, animated: false)
}
}
停止两个表格的弹跳效果。
tableViewLeft.bounces = false
tableViewRight.bounces = false
tableViewLeft.showsVerticalScrollIndicator = false
tableViewRight.showsVerticalScrollIndicator = false
在Swift中对称滚动两个UITableView:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if tb_time1 == scrollView {
tb_time2.contentOffset = tb_time1.contentOffset
}else if tb_time2 == scrollView {
tb_time1.contentOffset = tb_time2.contentOffset
}
}
scrollViewDidScroll(_ scrollView: UIScrollView)
方法? - luke