最近項目有個需求,實現滑動視圖(比如scrollerview)的滾動條一直顯示,初步以為很簡單,結果加上查閱資料,花了很長時間才解決這個問題,在這里跟大家做個簡單的分享。之前查閱的資料,都歸結為SetAlpha,貼出一個比較有代表性的代碼片段(截圖,感興趣的可以去網上搜)。
#define noDisableVerticalScrollTag 836913
#define noDisableHorizontalScrollTag 836914
@implementation UIImageView (ForScrollView)
- (void) setAlpha:(float)alpha {
if (self.superview.tag == noDisableVerticalScrollTag) {
if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleLeftMargin) {
if (self.frame.size.width < 10 && self.frame.size.height > self.frame.size.width) {
UIScrollView *sc = (UIScrollView*)self.superview;
if (sc.frame.size.height < sc.contentSize.height) {
return;
}
}
}
}
if (self.superview.tag == noDisableHorizontalScrollTag) {
if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleTopMargin) {
if (self.frame.size.height < 10 && self.frame.size.height < self.frame.size.width) {
UIScrollView *sc = (UIScrollView*)self.superview;
if (sc.frame.size.width < sc.contentSize.width) {
return;
}
}
}
}
[super setAlpha:alpha];
}
@end
這個方法寫的好像蠻有邏輯,我嘗試了一下沒有成功(可能是因為我當時在scrollerview的父視圖的XIB文件上創建的imageview?),索性換了一個寫法,我個人覺得是比較合適的,具體邏輯如下:
1?.將原有的showsVerticalScrollIndicator
屬性設置為NO,隱藏了原有的滾動提示條。
2?.在XIB文件上創建一個Imageview ,設置顏色,準備用它來做指示滾動條,設置顏色初始位置等(代碼創建也可以)。
3?.在系統的這個方法里面- (void)scrollViewDidScroll:(UIScrollView *)scrollView
,根據scrollerview或者collectionview的Contentsize
做邏輯運算(只要在拖動的時候就會執行這個方法)。
4?.將試圖外滾動條的多余部分做成不顯示的效果。
以上就是較為簡單的邏輯,下面是代碼的實現部分:
創建完畢后(_mCollectionView
是需要一直顯示滾動條的scrollerview,_mImageIndicator
是用xib創建的imageview類型的指示條),實現代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// CGPoint contentCenter=_mCollectionView.contentOffset;
// NSLog(@"原點%@",NSStringFromCGPoint(contentCenter));
// _mImageIndicator.center=CGPointMake(_mImageIndicator.center.x, contentCenter.y);
float zoom = 0;
zoom= scrollView.contentOffset.y/(scrollView.contentSize.height -scrollView.frame.size.height+(_mImageIndicator.frame.size.height-_mImageIndicator.frame.size.height*scrollView.frame.size.height/scrollView.contentSize.height));
_mImageIndicator.frame=CGRectMake(_mCollectionView.frame.size.width-3,zoom*scrollView.contentSize.height*216/kScreenHeight,3,_mImageIndicator.frame.size.height);
NSLog(@"offset.y:%f",scrollView.contentOffset.y);
NSLog(@"indicator.y:%f",_mImageIndicator.frame.origin.y);
}
216/kScreenHeight
這個是scrollerview本身的寬度和屏幕寬度的比例(如果你的scrollerview或者collectionview展示滿了整個屏幕,那就不需要乘以這個比例)
Demoviewcontroller
是collectionview的父視圖,設置它的clipsToBounds
屬性為YES,讓指示條的多余部分不顯示即可。
運行,完美實現功能,首篇簡書,歡迎指正0.0