我想在他们的列表中模拟twitter或instagram的行为:
在UITabBarItem中双击时,列表将滚动到顶部。有人知道我该怎么做? 我的UITabBarController中有4个项目,所有这些都是列表,所以我想为所有人做这件事。
问题是当我在mi列表的推送视图中点击条形项时,此函数在获取导航的根视图控制器之前调用并检测双击。
我希望能解决我的问题。
var previousController: UIViewController?
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
if previousController == viewController{
if let navVC = viewController as? UINavigationController, vc = navVC.viewControllers.first as? HomeViewController {
vc.tableBusinessList.setContentOffset(CGPointZero, animated: true)
print("same")
}
}else{
print("No same")
}
previousController = viewController
}
行为不正确。 当我使用标签栏项目弹出视图时,根视图位于单元格0
上答案 0 :(得分:10)
好的,我认为最好的方法是检查带有tableView的viewController是否可见,如果不可见,则不要调用set content offset。
所以:
var previousController: UIViewController?
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
if previousController == viewController {
if let navVC = viewController as? UINavigationController, vc = navVC.viewControllers.first as? HomeViewController {
if vc.isViewLoaded() && (vc.view.window != nil) {
// viewController is visible
vc.tableBusinessList.setContentOffset(CGPointZero, animated: true)
}
print("same")
}
}else{
print("No same")
}
previousController = viewController
}
答案 1 :(得分:2)
Swift 3
extension UIViewController {
func scrollToTop() {
func scrollToTop(view: UIView?) {
guard let view = view else { return }
switch view {
case let scrollView as UIScrollView:
if scrollView.scrollsToTop == true {
scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: true)
return
}
default:
break
}
for subView in view.subviews {
scrollToTop(view: subView)
}
}
scrollToTop(view: self.view)
}
}
如何使用
var previousController: UIViewController?
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//when user is in FeedViewController and scroll at last record and want to
if previousController == viewController {
if let navVC = viewController as? UINavigationController, let vc = navVC.viewControllers.first as? HomeViewController {
if vc.isViewLoaded && (vc.view.window != nil) {
vc.scrollToTop()
}
print("same")
}
}
else{
print("No same")
}
previousController = viewController
return true;
}
注意:我使用@Olivier Wilkinson并展示如何在所需位置使用扩展滚动到顶部。 (经过集合视图测试)
答案 2 :(得分:1)
Olivier Wilkinsons的答案很棒,但滚动部分在Swift 4中不再起作用,所以请替换
vc.tableBusinessList.setContentOffset(CGPointZero, animated: true)
与
vc.tableBusinessList.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
你已经完成了