I have CollectionView
and TableView
in a controller . I have made a segment control
by CollectionView
and implements scrollView
delegate in controller
like below :-
class MyViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,UICollectionViewDelegateFlowLayout
I have implements scrollViewDidEndDecelerating
, Now i want to detect which component scrolling (tableView or 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()
}
}
}
Since UICollectionView
and UITableView
inherit from UIScrollView
you can use an if let
to attempt to cast the UIScrollView
to either, which will then reveal which it is:
extension ViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if let _ = scrollView as? UITableView {
print("tableview")
} else if let _ = scrollView as? UICollectionView {
print("collectionview")
}
}
}
Alternatively, if you have properties stored for the UITableView
and UICollectionView
, you could use an equality check on the scrollView
passed to scrollViewDidEndDecelerating(_:)
to determine which is which:
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")
}
}
}