2011-10-06 56 views
0

如果我有一个UIView作为UIScrollView的子视图,并且这个滚动视图是一个水平滚动视图,我怎么知道UIView(子视图)何时不在UIScrollView中,以便我可以删除它作为子视图并将其存储在其他地方以供重用?有这样的代表吗?UISiew里面的UIScrollView问题

+1

什么是总体使用情况?通常你会把UIView放在那里,以便当他们回滚时。 –

+0

用例是我想拥有一个UIView池,因为在屏幕上每次只有3个子视图。当他们回滚时,我想从我的池中重用UIView。有点像UITableView单元,你可以重用 – xonegirlz

回答

0

是的,这是一个委托,你需要使用UIScrollViewDelegate。

http://developer.apple.com/library/IOS/#documentation/UIKit/Reference/UIScrollViewDelegate_Protocol/Reference/UIScrollViewDelegate.html

的方法scrollViewDidScroll告诉你,当滚动追加,所以在这个功能,你可以测试contentOffset财产(scrollview.contentOffset.x),然后将它与您的视图的位置和大小比较(myView.frame.origin.x + myView.frame.size.width)。

所以basicaly你应该做的

if(scrollview.contentOffset.x > (myView.frame.origin.x + myView.frame.size.width)) 
//Remove my view to reuse it 

如果你只有2次显示,只是想重新使用每个视图中,你可以找到当前显示的是这样的观点:

//Assuming your views had the same width and it is store in the pageWidth variable 
    float currPosition = photoGalleryScrollView.contentOffset.x; 
    //We look for the selected page by comparing his width with the current scroll view position 
    int selectedPage = roundf(currPosition/pageWidth); 
    float truePosition = selectedPage * pageWidth; 
    int zone = selectedPage % 2; 
    BOOL view1Active = zone == 0; 
    UIView *nextView = view1Active ? view2 : view1; 
    UIView *currentView = view1Active ? view1 : view2; 

    //We search after the next page 
    int nextpage = truePosition > currPos + 1 ? selectedPage-1 : selectedPage+1; 

    //then we compare our next page with the selectd page 
    if(nextpage > selectedPage){ 
     //show next view 
    } 
    else{ 
     //show previous view 
    } 

之后,您需要向nextView添加一些内容,将其添加到滚动视图并在隐藏时删除currentView。

+0

如果我想知道这个视图是否因为用户水平向左或向右水平滑动而消失了,该怎么办? – xonegirlz

0

您可以使用UIScrollViewDelegate方法scrollViewDidEndDecelerating:和一些自定义代码来实现此目的。

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    //set theScrollView's delegate 
    theScrollView.delegate = self; 
} 

//custom method for determining visible rect of scrollView 
- (CGRect)visibleRectForScrollView:(UIScrollView *)scrollView; { 
    CGFloat scale = (CGFloat) 1.0/scrollView.zoomScale; 
    CGRect visibleRect; 
    visibleRect.origin = scrollView.contentOffset; 
    visibleRect.size = scrollView.bounds.size; 
    float theScale = 1.0/scale; 
    visibleRect.origin.x *= theScale; 
    visibleRect.origin.y *= theScale; 
    visibleRect.size.width *= theScale; 
    visibleRect.size.height *= theScale; 
    return visibleRect; 
} 

//UIScrollView Delegate method 
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
    BOOL viewVisisble = CGRectContainsRect([self visisbleRectForScrollView:theScrollView], theView.frame); 
    if(!viewVisisble) { 
     //do something 
    } 
} 
+0

visibleRect是一个CGRect,但你正在返回一个CGFloat? – xonegirlz

+0

显然这是一个错误,你可以看到它说CGRect在代码中的方法 –