跟随 UICollectionView 指示器的 UIView

UIView that follows UICollectionView indicator

我想创建一个包含 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 = p.y;
    self.indicatorView.frame = indicatorFrame;
}

但是 indicatorView 并没有完全跟随指标!!

这对我有用:请查看附加的 gif。我添加了与 scrool 指示器平行的蓝色自定义 uiview。

我尝试了 table 视图,但这也适用于集合视图。

-(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:

请注意,我使用了 indicatorView 的示例值 postion.You 可以根据您的需要替换这些值。

indicatorView=[[UIView alloc]initWithFrame:CGRectMake( p.x, p.y , 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; 
}