1. 程式人生 > >scrollview設定滾動方向、自定義翻頁效果尺寸

scrollview設定滾動方向、自定義翻頁效果尺寸

一、設定滾動方向

禁止UIScrollView垂直方向滾動,只允許水平方向滾動

scrollview.contentSize =  CGSizeMake(你要的長度, 0); 

禁止UIScrollView水平方向滾動,只允許垂直方向滾動

scrollview.contentSize =  CGSizeMake(0, 你要的寬度); 

注意事項:

但是即使設定了contentSize的大小,還是有個坑要注意一下:因為contenInset值被意外修改過的時候,scrollview仍然可以滑動。

再配上UINavigationController每次push後再pop回來的情景,UIScrollView的contenInset

都會重寫改變重置,下面是KVO監測到的資料:


這種問題對於經驗不久的新手來說很難定位到問題的所在。

下面是我在此複合情景中禁止scrollView上下滑動處理方法:

//設定contentSize    
scrollView.contentSize = CGSizeMake(ksScreenWidth, 0);
    [scrollView addObserver:self forKeyPath:@"contentInset" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

//重寫observeValueForKeyPath方法
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary *)change
                      context:(void *)context
{

    if ([keyPath isEqual:@"contentInset"])
    {

        NSlog(@"contentSize被改變了");
        NSlog(@"\n contentInset新:%@\n contentInset老:%@", [change objectForKey:@"new"],[change objectForKey:@"old"]);
        if (object == scrollView) {
            
            UIEdgeInsets insets =[[change objectForKey:@"new"] UIEdgeInsetsValue] ;

            
            if (insets.bottom>0||insets.top>0) {
                
                scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

            }
            
        }
    }

}


- (void)dealloc
{
    /**
     *  移除監聽
     */
    [scrollView removeObserver:self forKeyPath:@"contentInset"];
}


二、自定義翻頁效果尺寸

UISCrollView在設定屬性pagingEnable=YES時會有一個自帶的滑動翻頁效果,預設的滑動翻頁尺寸是螢幕的寬(或者高)的整數倍,在某些場景下我們需要自定義滑動翻頁的尺寸,只需要修改下面這個代理方法的
targetContentOffset引數,
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset;


這個方法在pagingEnable=YES的時候也會呼叫; 但是pagingEnable的效果會覆蓋這個方法的效果,達不到我們想要的“剛好停到指定位置的效果”,所以還是需要注意將pagingEnable設定為NO! 示例程式碼:
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGPoint originalTargetContentOffset = CGPointMake(targetContentOffset->x, targetContentOffset->y);
    CGPoint targetCenter = CGPointMake(0,0);//目標位置
     *targetContentOffset = targetCenter;
   
}
參考地址:http://www.cnblogs.com/Phelthas/p/4584645.html

還有另外一種更全面的方案,參考:http://www.cnblogs.com/silence-cnblogs/p/6529728.html