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

在ViewController.h文件中添加以下代码:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

在ViewController.m文件中添加以下代码:

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UILabel *agreementLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建UILabel
    self.agreementLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 30)];
    [self.view addSubview:self.agreementLabel];
    
    // 设置UILabel的属性
    self.agreementLabel.userInteractionEnabled = YES;
    self.agreementLabel.text = '同意用户协议和隐私协议';
    
    // 创建NSMutableAttributedString
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.agreementLabel.text];
    
    // 设置蓝色
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, attributedString.length)];
    
    // 设置下划线
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, attributedString.length)];
    
    // 添加点击事件
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(agreementLabelTapped)];
    [self.agreementLabel addGestureRecognizer:tapGesture];
    
    // 设置UILabel的attributedText
    self.agreementLabel.attributedText = attributedString;
}

- (void)agreementLabelTapped {
    // 点击事件处理
    NSLog('用户点击了协议');
}

@end

这样,当用户点击同意用户协议和隐私协议的UILabel时,会触发agreementLabelTapped方法。您可以在该方法中处理点击事件。

iOS开发:UILabel实现同意用户协议和隐私协议文字变蓝色可点击 - 详细代码

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

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