前言:
- 最近研究了一下iOS中頂部滑塊的簡單實現
- 之前一直都是用第三方的,突然感覺應該自己寫一個,就去網上研究了一下,現在把成果給大家分享一下。
具體效果如圖:
首先說一下主要的幾個代碼段:
1. 主要控件的初始化:
UIScrollView *scrollView//滾動視圖
UIView *alphaView//蒙版
UIView *theSubView//底層圖層
UIView *theFrontView//頂層圖層
2. 設置底層圖層:
2.1加載底層圖層主體部分
- (UIView *)theSubView {
// 添加前景色
UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 70)];
backView.backgroundColor = [UIColor colorWithRed:0.922 green:0.922 blue:0.922 alpha:1];
[self.view addSubview:backView];
return backView;
}
2.2添加左邊的標題
// 標題1
UILabel *title1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 160, 70)];
title1.text = @"偶然";
title1.textAlignment = NSTextAlignmentCenter;
title1.font = [UIFont systemFontOfSize:20.f];
title1.textColor = [UIColor colorWithRed:0.443 green:0.439 blue:0.439 alpha:1];
[backView addSubview:title1];
2.3添加右邊的標題
// 標題2
UILabel *title2 = [[UILabel alloc] initWithFrame:CGRectMake(210, 0, 160, 70)];
title2.text = @"無心";
title2.textAlignment = NSTextAlignmentCenter;
title2.font = [UIFont systemFontOfSize:20.f];
title2.textColor = [UIColor colorWithRed:0.443 green:0.439 blue:0.439 alpha:1];
[backView addSubview:title2];
注意:
字體建議選居中顯示,字體顏色和背景色盡量容易區分。
3. 設置頂層圖層:
3.1加載頂層圖層主體部分
- (UIView *)theFrontView {
// 添加前景色
UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 70)];
backView.backgroundColor = [UIColor colorWithRed:0.808 green:0.208 blue:0.212 alpha:1];
[self.view addSubview:backView];
return backView;
}
注意:
頂層圖層的背景顏色盡量和底層圖層背景顏色有明顯區分,方便使用者的辨認當前位置。
3.2-3.3左右標題的添加
左右標題和底層圖層一樣,除了字體顏色和backView顏色,略過
注意:
字體顏色和頂層圖層背景色容易區分
重點:
4. 設置蒙版層:
self.alphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, 190, 50)];
self.alphaView.backgroundColor = [UIColor blackColor];
self.alphaView.layer.cornerRadius = 15.f;
backView.maskView = self.alphaView;
注意:
將此圖層設置為頂層的backView的maskView(蒙版),可通過它的位置改變來控制顯示頂層圖層的內容范圍。
5. 設置蒙版層和scrollView的移動關系:
這里我們把每次scrollView被拖動的x的偏移量坐標的相對距離給到頂層蒙版,使頂層蒙版發生對應的位置偏移,這樣就顯示出不同的頂層區域,而沒有被覆蓋的則顯示底層區域。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGRect rect = self.alphaView.frame;
rect.origin.x = scrollView.contentOffset.x / 2.f;
self.alphaView.frame = rect;
}
注意:
1.這里我們直接使用scrollView的拖拽方法,記得設置scrollView的代理為self,并在頂部遵守協議<UIScrollViewDelegate>!
2.圖層的層次關系,如下如:
完整代碼已上傳到github,歡迎下載
https://github.com/ouranou/Topslider