遵循UICollectionView指标的UIView

时间:2015-09-08 14:52:26

标签: ios objective-c uiscrollview uicollectionview indicator

我想创建一个包含UIImageView和UILabel的自定义UIView,它指向UICollectionView滚动指示器,并随之滚动。

enter image description here

我正在使用此代码:

- (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;
}

但是指标视图并不完全符合指标!!

2 个答案:

答案 0 :(得分:2)

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

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

enter image description here

-(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的示例值。您可以根据需要替换它们。

indicatorView=[[UIView alloc]initWithFrame:CGRectMake( p.x, p.y , 10, 10)];

indicatorView.backgroundColor=[UIColor blueColor];

[self.tableView addSubview:indicatorView];

答案 1 :(得分:0)

对我而言,这有效:

....
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; 
}