看到有些APP在tableView右側增加了一個滾動標簽,并且顯示滑條所指向的cell的部分數據。這里寫下自己的想法,實現還是簡單的。
效果圖:
效果圖
想到的方法一:
- 剛開始打算自己創建一個UILabel索引標簽,然后監聽tableView的contentOffset來實現索引標簽的移動:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// 在這里根據scrollView.contentOffset.y來改變標簽索引的坐標
// contentSize的高度,和屏幕高度是成固定比例的,所以可以計算出來
}
后來感覺這樣太麻煩,于是就打算監聽scrollview內部的導航view決定索引標簽的移動。由于是scrollView的內部控件,所以就通過斷點的方式獲取控件的成員變量名:
斷點
看出成員變量名如下:
成員變量名
由此可以引出方法二和三。
方法二:
- 還是采用創建UILabel,不過是加到控制器的view上,然后根據其中的_verticalScrollIndicator的左邊,來進行相應的移動。
由于此標簽索引不需要交互,所以我采用了方法三。
方法三:
- 將創建的UILabel添加到_verticalScrollIndicator上,成為它的子控件。然后通過indexPathForRowAtPoint:獲取對應的cell的行號。因為_verticalScrollIndicator本身是和tableView在同一個坐標系,所以也不需要做轉換。
主要代碼如下:
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) UILabel *indicatorView;
@property (weak, nonatomic) UIView *scrollIndicator;
@end
static NSString *const reuseIndentifier = @"testCell";
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.rowHeight = 150;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 200;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIndentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIndentifier];
}
cell.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:0.5];
cell.textLabel.text = [NSString stringWithFormat:@"just a function test--%ld!", indexPath.row];
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
UITableView *tableView = (UITableView *)scrollView;
// 在這里根據_verticalScrollIndicator的中點,來獲取對應的cell行號,從而可以獲取對應行的數據來進行顯示
self.indicatorView.text = [NSString stringWithFormat:@"%ld", [tableView indexPathForRowAtPoint:self.scrollIndicator.center].row];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 這里注意要在點擊時獲取,如果在view加載完成時設置標簽索引的中點,那么獲取的_verticalScrollIndicator的frame是不對的
if (!self.indicatorView) {
self.scrollIndicator = [self.tableView valueForKey:@"verticalScrollIndicator"];
UILabel *indicatorView = [[UILabel alloc] initWithFrame:CGRectMake(-50, 0, 50, 20)];
indicatorView.backgroundColor = [UIColor orangeColor];
CGPoint center = indicatorView.center;
center.y = self.scrollIndicator.bounds.size.height * 0.5;
indicatorView.center = center;
[self.scrollIndicator addSubview:indicatorView];
self.indicatorView = indicatorView;
}
}
@end