iOS 开发:UILabel 实现 同意用户协议和隐私协议 文字变蓝可点击 (OC 代码)
在 iOS 开发中,你可以使用 UILabel 的富文本属性来实现同意用户协议和隐私协议中的文字变蓝色可点击的效果。下面是一个 OC 代码示例:
// 创建一个 UILabel 并设置其属性
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 40)];
label.numberOfLines = 0;
label.userInteractionEnabled = YES;
// 创建一个 NSMutableAttributedString,并设置其属性
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:'同意用户协议和隐私协议'];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(2, 4)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(9, 4)];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(2, 4)];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(9, 4)];
// 设置 UILabel 的富文本属性
label.attributedText = attributedString;
// 添加一个点击手势
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped)];
[label addGestureRecognizer:tapGesture];
// 将 UILabel 添加到视图中
[self.view addSubview:label];
// 点击手势的响应方法
- (void)labelTapped {
NSLog('用户协议被点击了');
}
在上述代码中,我们创建了一个 UILabel,并设置其 numberOfLines 为 0 以支持多行文本显示。然后,我们创建了一个 NSMutableAttributedString 对象,并设置其属性,包括将指定范围内的文字颜色设置为蓝色,并添加下划线效果。接下来,将 NSMutableAttributedString 对象设置为 UILabel 的 attributedText 属性,从而实现了文字变蓝色可点击的效果。
最后,我们添加了一个点击手势,当用户点击 UILabel 时,会触发 labelTapped 方法,我们可以在该方法中处理用户点击操作。
原文地址: https://www.cveoy.top/t/topic/XGr 著作权归作者所有。请勿转载和采集!