以下是用UILabel实现同意用户协议和隐私协议,使文字变蓝色可点击的详细代码:

  1. 创建UILabel并设置属性:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, self.view.frame.size.width - 40, 30)];
label.textAlignment = NSTextAlignmentCenter;
label.numberOfLines = 0;
label.text = '我已阅读并同意用户协议和隐私协议';
label.font = [UIFont systemFontOfSize:14];
[self.view addSubview:label];
  1. 创建NSMutableAttributedString并设置点击属性:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(7, 4)]; // 设置用户协议为蓝色可点击
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(12, 4)]; // 设置隐私协议为蓝色可点击
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(7, 4)]; // 添加下划线
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(12, 4)]; // 添加下划线
label.attributedText = attributedString;
  1. 添加点击事件处理:
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
[label addGestureRecognizer:tapGesture];
label.userInteractionEnabled = YES;
  1. 实现点击事件处理方法:
- (void)tapGesture:(UITapGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:gesture.view];
    
    // 获取点击的字符索引
    NSUInteger index = [self characterIndexAtPoint:point label:gesture.view];
    
    // 判断点击的是用户协议还是隐私协议
    if (index >= 7 && index <= 10) {
        // 点击了用户协议
        NSLog('点击了用户协议');
    } else if (index >= 12 && index <= 15) {
        // 点击了隐私协议
        NSLog('点击了隐私协议');
    }
}

- (NSUInteger)characterIndexAtPoint:(CGPoint)point label:(UILabel *)label {
    // 创建一个文字容器
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];
    
    // 创建一个布局管理器
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [textStorage addLayoutManager:layoutManager];
    
    // 创建一个文字容器尺寸
    CGSize containerSize = CGSizeMake(label.bounds.size.width, CGFLOAT_MAX);
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:containerSize];
    textContainer.lineFragmentPadding = 0;
    [layoutManager addTextContainer:textContainer];
    
    // 根据点击位置获取字符索引
    NSUInteger characterIndex = [layoutManager characterIndexForPoint:point inTextContainer:textContainer fractionOfDistanceBetweenInsertionPoints:nil];
    
    return characterIndex;
}

通过以上代码,就可以实现UILabel上的文字变蓝色可点击的效果。当用户点击用户协议或隐私协议时,可以在点击事件处理方法中做相应的处理。


原文地址: https://www.cveoy.top/t/topic/XM1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录