我在控制器中有CollectionViewTableView。我已经用segment control制作了CollectionView,并在scrollView中实现了controller 代表,如下所示:-

class MyViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,UICollectionViewDelegateFlowLayout

我已经实现了scrollViewDidEndDecelerating,现在我想检测哪个组件滚动(tableView或collectionView)
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
    {
         //here i want to detect which component scrolling(tableView or collectionView)

        if scrollView.contentOffset.x == 0
        {
            segmentControl.selectedSegmentIndex = 0
            DispatchQueue.main.async{
                self.colView.reloadData()
            }
        }
        else if scrollView.contentOffset.x == view.frame.size.width
        {
            DispatchQueue.main.async{
                self.colView.reloadData()
            }
            segmentControl.selectedSegmentIndex = 1
        }
        DispatchQueue.main.async{

                let segAttributes: NSDictionary = [
                    NSForegroundColorAttributeName: UIColor.white,
                    NSFontAttributeName: UIFont.systemFont(ofSize: 12)
                ]
                let segAttributes1: NSDictionary = [
                    NSForegroundColorAttributeName: UIColor.init(red: 247.0/255.0, green: 105.0/255.0, blue: 8.0/255.0, alpha: 1),
                    NSFontAttributeName: UIFont.systemFont(ofSize: 12)
                ]


                self.segmentControl.setTitleTextAttributes(segAttributes1 as [NSObject : AnyObject], for: UIControlState.selected)
                self.segmentControl.setTitleTextAttributes(segAttributes as [NSObject : AnyObject], for: UIControlState.normal)
                self.tblVIewAmenities.reloadData()
                self.tblViewRoomDetails.reloadData()
            }

        }

    }

最佳答案

由于UICollectionViewUITableView继承自UIScrollView,因此您可以使用if let尝试将UIScrollView强制转换为任意一个,然后将其显示为:

extension ViewController: UIScrollViewDelegate {
  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if let _ = scrollView as? UITableView {
      print("tableview")
    } else if let _ = scrollView as? UICollectionView {
      print("collectionview")
    }
  }
}

另外,如果您存储了UITableViewUICollectionView的属性,则可以对传递给scrollViewscrollViewDidEndDecelerating(_:)进行相等检查,以确定哪个:
class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var tableView: UITableView!
}

extension ViewController: UIScrollViewDelegate {
  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if scrollView == tableView {
      print("tableview")
    } else if scrollView == collectionView {
      print("collectionview")
    }
  }
}

10-08 17:45