viewWillAppear用于子视图

nan*_*nan 23 iphone uiscrollview uiview

我有UIScrollView与多个UIVIew子视图.我想更新每个UIView出现在UIScrollView可见部分时显示的数据.

什么是触发的回调?我试过了viewWillAppear,但它似乎没有被调用.

谢谢.:)

Ole*_*ann 90

你必须自己做计算.scrollViewDidScroll:在滚动视图中实现委托并手动计算哪些视图是可见的(例如,通过检查是否CGRectIntersectsRect(scrollView.bounds, subview.frame)返回true).

  • 正是我需要的,并允许我避免一堆手动计算. (2认同)

Lun*_*s42 9

Swift 3解决方案

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let viewFrame = greenView.frame

    let container = CGRect(x: scrollView.contentOffset.x, y: scrollView.contentOffset.y, width: scrollView.frame.size.width, height: scrollView.frame.size.height)


    // We may have received messages while this tableview is offscreen
    if (viewFrame.intersects(container)) {
        // Do work here
        print("view is visible")
    }
    else{
        print("nope view is not on the screen")
    }
}
Run Code Online (Sandbox Code Playgroud)


Mih*_*hta 6

如果您的滚动视图未处于放大状态,则上述答案是正确的.万一你的滚动视图可以放大以上计算将无法工作,因为你也需要考虑缩放

这是代码

CGRect visibleRect;
               visibleRect.origin = self.mapScrollView.contentOffset;
                visibleRect.size = self.mapScrollView.bounds.size;

                float theScale = 1.0 / self.mapScrollView.zoomScale;
                visibleRect.origin.x *= theScale;
                visibleRect.origin.y *= theScale;
                visibleRect.size.width *= theScale;
                visibleRect.size.height *= theScale;
                if(CGRectIntersectsRect(visibleRect, btnPin.frame)){
                      ...
                }
Run Code Online (Sandbox Code Playgroud)


Chr*_*nce 5

稍微改进一下.我想知道scrollview中显示的视图数量:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    // Figure out how much of the self.userFeedbackView is displayed.
    CGRect frame = CGRectIntersection(self.scrollView.bounds, self.userFeedbackView.frame);
    CGFloat proportion = (frame.size.height*frame.size.width)/(self.userFeedbackView.frameWidth*self.userFeedbackView.frameHeight);
    NSLog(@"%f; %@", proportion, NSStringFromCGRect(frame));
}
Run Code Online (Sandbox Code Playgroud)