造轮子 - UITableView字母索引条

4,007 阅读2分钟

最近重构项目的通信录页面,旧版本的索引条相当丑陋,找了下轮子又找不到,没办法,只能自己造了。发现微信的通讯录索引条样式还不错,照着写了一个,顺便添加了震动效果(Impact Feedback)。

首先看一下效果

单击索引条时

单击索引条字母

滑动tableView时

滑动tableView时.gif

在索引条上滑动时

在索引条上滑动时.gif

实现原理

1、每个索引都是UILabel

把所有label都竖直排列在一个父view中。这里没有使用重用池,主要考虑到一般的索引条,字母数量也不会太多。

_labelArr = [NSMutableArray new];
for (int i = 0; i < indexes.count; i++) {
    CGFloat y = (_sectionHeight * i);
    
    UILabel *alphaLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    alphaLabel.textAlignment = NSTextAlignmentCenter;
    alphaLabel.text = [[indexes objectAtIndex:i] uppercaseString];
    alphaLabel.font = [UIFont boldSystemFontOfSize:10.0];
    alphaLabel.backgroundColor = [UIColor clearColor];
    alphaLabel.textColor = self.textColor;
    alphaLabel.layer.cornerRadius = width * 0.5;
    alphaLabel.clipsToBounds = YES;
    [self addSubview:alphaLabel];
    [_labelArr addObject:alphaLabel];
}
2、关联触摸点和索引label

当在父view中触摸时,通过touchMoved等方法处理触摸点和索引label之间的关系,如果触摸点落在label范围之内,则将label高亮选中。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    
    CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
    [self toSelectTitle:touchPoint];
}

// 通过touchPoint找到对应的索引label
- (void)toSelectTitle:(CGPoint)touchPoint
{
    if(touchPoint.x <= 0 ||
       touchPoint.y <= 0 ||
       touchPoint.x >= self.bounds.size.width ||
       touchPoint.y >= self.bounds.size.height) return;
    __block NSString *title;
    __block NSInteger index = 0;
    
    [_labelArr enumerateObjectsUsingBlock:^(__kindof UILabel * _Nonnull subview, NSUInteger idx, BOOL * _Nonnull stop) {
        if(touchPoint.y < CGRectGetMaxY(subview.frame)) {
            _preLabel.backgroundColor = [UIColor clearColor];
            _preLabel.textColor = _textColor;
            
            subview.backgroundColor = _selectedBackgroundColor;
            subview.textColor = _selectedTextColor;
            _preLabel = subview;
            
            index = idx;
            title = subview.text;
            *stop = YES;
        }
    }]; 

    ......
}
3、添加震动效果

添加震动效果,并触发点击回调

//震动
if (@available(iOS 10.0, *)) {
    UIImpactFeedbackGenerator *gen = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
    [gen prepare];
    [gen impactOccurred];
}
    
//回调
if (_delegate && [_delegate conformsToProtocol:@protocol(TTIndexBarDelegate)]) {
    [_delegate indexDidChanged:self index:index title:title];
}
4、选中气泡的实现
- (void)drawRect:(CGRect)rect {
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetFillColorWithColor(context,_drawColor.CGColor);
    [self getDrawPath:context];
    CGContextFillPath(context);
}

- (void)getDrawPath:(CGContextRef)context {
    
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    CGFloat xOffset = self.bounds.size.width * 1/4;
    CGFloat yOffset = self.bounds.size.height * 1/4;
    CGFloat radius = sqrt(pow(xOffset, 2) + pow(yOffset, 2));
    
    //Draw triangle
    CGContextMoveToPoint(context, width - xOffset, height * 0.5 - yOffset);
    CGContextAddLineToPoint(context,width, height * 0.5);
    CGContextAddLineToPoint(context,width - xOffset, height * 0.5 + yOffset);
    
    //Draw semicircle
    CGContextAddArcToPoint(context, width * 0.5, height, width * 0.5 - xOffset, height * 0.5 + yOffset, radius);
    CGContextAddArcToPoint(context, 0, height * 0.5, width * 0.5 - xOffset, height * 0.5 - yOffset, radius);
    CGContextAddArcToPoint(context, width * 0.5, 0, width * 0.5 + xOffset, height * 0.5 - yOffset, radius);
    CGContextClosePath(context);
}

如何使用

默认样式
self.indexBar = [[TTIndexBar alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 30, 0, 30, self.view.frame.size.height)];
self.indexBar.delegate = self;
[self.view addSubview:self.indexBar];
    
[self.indexBar setIndexes:[NSMutableArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J", nil]];
自定义样式
self.indexBar = [[TTIndexBar alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 30, 0, 30, self.view.frame.size.height)];
self.indexBar.delegate = self;
[self.view addSubview:self.indexBar];   

//Custom property
self.indexBar.textColor = [UIColor redColor];
self.indexBar.selectedTextColor = [UIColor greenColor];
self.indexBar.selectedBackgroundColor = [UIColor yellowColor];
self.indexBar.detailViewDrawColor = [UIColor cyanColor];
self.indexBar.detailViewTextColor = [UIColor orangeColor];

[self.indexBar setIndexes:[NSMutableArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J", nil]];
代理回调
- (void)indexDidChanged:(TTIndexBar *)indexBar index:(NSInteger)index title:(NSString *)title;

GitHub

TTIndexBar

源码中的英文注释都是自己写的,有点抠脚😂 可能大家更想看中文注释

如有任何问题或建议,请下方留言,谢谢。