UIView遵循UICollectionView指标

我想创build一个包含UIImageView和UILabel的自定义UIView,它指向UICollectionView的滚动指标,并与它滚动。

在这里输入图像说明

我正在使用这个代码:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView { //get refrence of vertical indicator UIImageView *verticalIndicator = ((UIImageView *)[scrollView.subviews objectAtIndex:(scrollView.subviews.count-1)]); // get the relative position of the indicator in the main window CGPoint p = [verticalIndicator convertPoint:verticalIndicator.bounds.origin toView:[[UIApplication sharedApplication] keyWindow]]; // set the custom view new position CGRect indicatorFrame = self.indicatorView.frame; indicatorFrame.origin.y = py; self.indicatorView.frame = indicatorFrame; } 

但indicatorView并没有完全按照指标!

这工作对我来说:请看附加的gif。 我已经添加了与蓝色平行的自定义uiview scrool指标。

我尝试了表视图,但这也适用于收集视图。

在这里输入图像说明

 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ dispatch_async(dispatch_get_main_queue(), ^{ //get refrence of vertical indicator UIImageView *verticalIndicator = ((UIImageView *)[scrollView.subviews objectAtIndex:(scrollView.subviews.count-1)]); // get the relative position of the indicator in the main window // CGPoint p = [verticalIndicator convertPoint:verticalIndicator.bounds.origin toView:[[UIApplication sharedApplication] keyWindow]]; CGPoint p = CGPointMake(verticalIndicator.frame.origin.x-10, verticalIndicator.frame.origin.y - scrollView.contentOffset.y); // set the custom view new position CGRect indicatorFrame = CGRectMake(verticalIndicator.frame.origin.x, verticalIndicator.frame.origin.y, 10, 10); self.indicatorView.frame = indicatorFrame; }); } 

也掩盖你确定你在查看加载方法中添加了uiview。

//在viewDidLoad

请注意,我已经使用指示器位置的示例值。您可以根据需要replace这些值。

 indicatorView=[[UIView alloc]initWithFrame:CGRectMake( px, py , 10, 10)]; indicatorView.backgroundColor=[UIColor blueColor]; [self.tableView addSubview:indicatorView]; 

对我来说这个工作:

 .... scrollIndicatorView = [self scrollIndicator]; [self.collectionView addSubview:scrollIndicatorView]; .... - (void)scrollViewDidScroll:(UIScrollView *)scrollView { // percentage of the content reached * height CGFloat yPos = (self.collectionView.contentOffset.y / (self.collectionView.contentSize.height - self.collectionView.bounds.size.height)) * self.collectionView.bounds.size.height; yPos += self.collectionView.contentOffset.y; // add content offset becasue view is inside colelctionview which content moves CGRect indicatorFrame = CGRectMake(self.collectionView.bounds.size.width - 10, yPos, 10, 30); scrollIndicatorView.frame = indicatorFrame; }