且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在iPhone中制作无限滚动视图?

更新时间:2023-09-23 07:48:39

首先,我建议使用UITableView,这样可以保持较低的内存使用率。我在项目中成功使用的方法如下:

    1。列表项

复制单元格的内容,我的意思是如果你有这样的5项:



| 1 | 2 | 3 | 4 | 5 |



你应该在表的末尾添加相同的(在具有可重用引擎的表视图中,这不是什么大不了的事),看起来像这样: / p>

| 1 | 2 | 3 | 4 | 5 | 1 | 2 | 3 | 4 | 5 |

    2。使用以下内容修改scrollViewDidScroll:



   - (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{
if(scrollView == _yourScrollView){
CGFloat currentOffsetX = scrollView.contentOffset.x;
CGFloat currentOffSetY = scrollView.contentOffset.y;
CGFloat contentHeight = scrollView.contentSize.height;

if(currentOffSetY<(contentHeight / 6.0f)){
scrollView.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY +(contentHeight / 2)));
}
if(currentOffSetY>((contentHeight * 4)/ 6.0f)){
scrollView.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY - (contentHeight / 2)));
}
}
}

上面的代码移动滚动如果你几乎达到滚动的最后一个位置在顶部;或者,如果你几乎在顶部,将你移到底部...

    3。就是这样。


I have a scrollview with 5 image views of width 88.

I want the scrollview to scroll to each image view (Not Paging)

and

I want to make an infinite scrollview in iPhone which means the when it scroll to last item it will display a first item next to it..

I have been trying by offset but it stops when move it by offset and also I have used apple street scroller which does not allow me to stop each element in center(just like Picker view)..

First of all, I recommend to use a UITableView so you can maintain the memory usage low. An approach that I had used successfully in a project is the following:

    1. List item

Duplicate the content of your cells, I mean if you have 5 items in this way:

| 1 | 2 | 3 | 4 | 5 |

You should add the same (In a table view with reusable engine that's not a big deal) at the end of the table in order to look like this:

| 1 | 2 | 3 | 4 | 5 | 1 | 2 | 3 | 4 | 5 |

    2. modify the scrollViewDidScroll with the following:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _yourScrollView) {
        CGFloat currentOffsetX = scrollView.contentOffset.x;
        CGFloat currentOffSetY = scrollView.contentOffset.y;
        CGFloat contentHeight = scrollView.contentSize.height;

        if (currentOffSetY < (contentHeight / 6.0f)) {
            scrollView.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY + (contentHeight/2)));
        }
        if (currentOffSetY > ((contentHeight * 4)/ 6.0f)) {
            scrollView.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY - (contentHeight/2)));
        }
    }
}

The code above move the scroll position at top if you almost reach the final of the scrolling; Or if you are almost on the top, moves you to the bottom...

    3. That's it.