iOS实现一段文字中部分有下划线,并且可以点击

项目中有一个需求就是实现一段文字中有几个特殊的字符可以有下划线,并且可以进行点击。
首先可以实现下划线效果,首先想到的是UILabel和UITextView控件的 NSMutableAttributedString 属性,考虑到可能会有点击事件效果的实现,这里选择UITextView控件,因为UITextView有一个功能就是能通过NSRange获得文字的相应的Frame。
最终实现这种效果,带下划线的可以点击,点击可以设置背景颜色,也可以不设置背景颜色,可以设置下换线以及下划线上面文字的颜色。


实现效果.png

1、首先创建UITextView类

创建UITextView.png

2、ClickTextView类中声明点击回调的block,这里回调用block进行回调

/** 点击回调的block */
typedef void(^clickTextViewPartBlock)(NSString *clickText);

3、介绍下主要的实现方法
1>、这个方法主要是将下划线对用的文字的frame,文字内容,点击效果背景颜色存储起来,以供点击的时候查询

/**
 *  设置textView的部分为下划线,并且使之可以点击
 *
 *  @param underlineTextRange 需要下划线的文字范围,如果NSRange范围超出总的内容,将过滤掉
 *  @param color              下划线的颜色,以及下划线上面文字的颜色
 *  @param coverColor         是否有点击的背景,如果设置相关颜色的话,将会有点击效果,如果为nil将没有点击效果
 *  @param block              点击文字的时候的回调
 */

- (void)setUnderlineTextWithRange:(NSRange)underlineTextRange withUnderlineColor:(UIColor *)color withClickCoverColor:(UIColor *)coverColor withBlock:(clickTextViewPartBlock)block
{
    if (self.text.length < underlineTextRange.location+underlineTextRange.length) {
        return;
    }
    
    // 设置下划线
    [self.content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:underlineTextRange];
    
    //设置文字颜色
    if (color) {
        [self.content addAttribute:NSForegroundColorAttributeName value:color range:underlineTextRange];
    }
    self.attributedText = self.content;
    
    // 设置下划线文字的点击事件
    // self.selectedRange  影响  self.selectedTextRange
    self.selectedRange = underlineTextRange;
    
    // 获取选中范围内的矩形框
    NSArray *selectionRects = [self selectionRectsForRange:self.selectedTextRange];
    // 清空选中范围
    self.selectedRange = NSMakeRange(0, 0);
    // 可能会点击的范围的数组
    NSMutableArray *selectedArray = [[NSMutableArray alloc] init];
    for (UITextSelectionRect *selectionRect in selectionRects) {
        CGRect rect = selectionRect.rect;
        if (rect.size.width == 0 || rect.size.height == 0) {
            continue;
        }
        // 将有用的信息打包<存放到字典中>存储到数组中
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        // 存储文字对应的frame,一段文字可能会有两个甚至多个frame,考虑到文字换行问题
        [dic setObject:[NSValue valueWithCGRect:rect] forKey:@"rect"];
        // 存储下划线对应的文字
        [dic setObject:[self.text substringWithRange:underlineTextRange] forKey:@"content"];
        // 存储相应的回调的block
        [dic setObject:block forKey:@"block"];
        // 存储对应的点击效果背景颜色
        [dic setValue:coverColor forKey:@"coverColor"];
        [selectedArray addObject:dic];
    }
    // 将可能点击的范围的数组存储到总的数组中
    [self.rectsArray addObject:selectedArray];
    
}

2>、通过一个点击的点,去查找有没有点在下划线对用的文字范围内,并且返回之前打包<存储的字典>的数据模型

- (NSArray *)touchingSpecialWithPoint:(CGPoint)point
{
    // 从所有的特殊的范围中找到点击的那个点
    for (NSArray *selecedArray in self.rectsArray) {
        for (NSDictionary *dic in selecedArray) {
            CGRect myRect = [dic[@"rect"] CGRectValue];
            if(CGRectContainsPoint(myRect, point) ){
                return selecedArray;
            }
        }
    }
    return nil;
}

3>、通过touchesBegan的方法,获取点击的点,并且去查询相关数据模型,并且根据参数是不是展示相应的点击效果,并且通过blcok进行回调

// 点击textView的 touchesBegan 方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 获取触摸对象
    UITouch *touch = [touches anyObject];
    
    // 触摸点
    CGPoint point = [touch locationInView:self];
    // 通过一个触摸点,查询点击的是不是在下划线对应的文字的frame
    NSArray *selectedArray = [self touchingSpecialWithPoint:point];
    for (NSDictionary *dic in selectedArray) {
        if(dic && dic[@"coverColor"]){
            UIView *cover = [[UIView alloc] init];
            cover.backgroundColor = dic[@"coverColor"];
            cover.frame = [dic[@"rect"] CGRectValue];
            cover.layer.cornerRadius = 5;
            cover.tag = kCoverViewTag;
            [self insertSubview:cover atIndex:0];
        }
    }
    if (selectedArray.count) {
        // 如果说有点击效果的话,加个延时,展示下点击效果,如果没有点击效果的话,直接回调
        NSDictionary *dic = [selectedArray firstObject];
        clickTextViewPartBlock block = dic[@"block"];
        if (dic[@"coverColor"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                block(dic[@"content"]);
            });
        }else{
            block(dic[@"content"]);
        }
    }
}

4>、点击结束的时候取消点击效果,也就是删除点击的时候创建的view

/** 点击结束的时候 */
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (UIView *subView in self.subviews) {
            if (subView.tag == kCoverViewTag) {
                [subView removeFromSuperview];
            }
        }
    });
}

/**
 *  取消点击的时候,清除相关的阴影
 */
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    for (UIView *subView in self.subviews) {
        if (subView.tag == kCoverViewTag) {
            [subView removeFromSuperview];
        }
    }
}

5、在ViewController中进行测试

 ClickTextView *clickTextView = [[ClickTextView alloc] initWithFrame:CGRectMake(50, 50, 300, 300)];
    [self.view addSubview:clickTextView];
    
    // 方便测试,设置textView的边框已经背景
    clickTextView.backgroundColor = [UIColor cyanColor];
    clickTextView.layer.borderWidth = 1;
    clickTextView.layer.borderColor = [UIColor redColor].CGColor;
    clickTextView.font = [UIFont systemFontOfSize:30];
    //clickTextView.textColor = [UIColor redColor];
    
    
    NSString *content = @"1234567890承诺书都差不多岁尺布斗粟CBD死UC收不到催上半场低俗";
    // 设置文字
    clickTextView.text = content;
    
    // 设置期中的一段文字有下划线,下划线的颜色为蓝色,点击下划线文字有相关的点击效果
    NSRange range1 = [content rangeOfString:@"承诺书都差"];
    [clickTextView setUnderlineTextWithRange:range1 withUnderlineColor:[UIColor blueColor] withClickCoverColor:[UIColor greenColor] withBlock:^(NSString *clickText) {
        NSLog(@"clickText = %@",clickText);
    }];
    
    // 设置期中的一段文字有下划线,下划线的颜色没有设置,点击下划线文字没有点击效果
    NSRange range2 = [content rangeOfString:@"不到催上半场低俗"];
    [clickTextView setUnderlineTextWithRange:range2 withUnderlineColor:nil withClickCoverColor:nil withBlock:^(NSString *clickText) {
        NSLog(@"clickText = %@",clickText);
    }];

如有失误请各位路过大神即时指点,或有更好的做法,也请指点一二。
详情Demo可参考

扩展:iOS 设置下划线与文字之间的距离

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Text Kit学习(入门和进阶): http://www.cocoachina.com/industry/201...
    F麦子阅读 4,137评论 1 13
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,180评论 4 61
  • 相比以前,更加的喜欢自己,才是最大的梦想,精神的释放
    alialiali阅读 147评论 0 0
  • 别后不知君远近,触目凄凉多少闷! 渐行渐远渐无书,水阔鱼沉何处问? 武汉·晴 今天阳光微醺,阳光偷偷爬近书桌,温...
    特别的猫呢阅读 664评论 0 5
  • 不管别人做了什么,我可以不生气吗? 曾经年轻的花姐,一年之中总会有那么几次情绪失控而生气,甚至气到歇斯底里,有时是...
    花姐瞎掰掰阅读 1,848评论 2 9