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

#import "ViewController.h"

@interface ViewController () <UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *agreementLabel;
@property (weak, nonatomic) IBOutlet UILabel *privacyLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置用户协议和隐私协议的文本
    NSString *agreementText = '同意用户协议';
    NSString *privacyText = '隐私协议';
    
    // 创建NSMutableAttributedString,并设置默认文本样式
    NSMutableAttributedString *agreementAttributedString = [[NSMutableAttributedString alloc] initWithString:agreementText];
    NSMutableAttributedString *privacyAttributedString = [[NSMutableAttributedString alloc] initWithString:privacyText];
    
    [agreementAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(2, 4)];
    [privacyAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 4)];
    
    // 设置UILabel的attributedText属性
    self.agreementLabel.attributedText = agreementAttributedString;
    self.privacyLabel.attributedText = privacyAttributedString;
    
    // 添加点击手势
    UITapGestureRecognizer *agreementTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(agreementLabelTapped:)];
    UITapGestureRecognizer *privacyTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(privacyLabelTapped:)];
    
    self.agreementLabel.userInteractionEnabled = YES;
    [self.agreementLabel addGestureRecognizer:agreementTapGesture];
    
    self.privacyLabel.userInteractionEnabled = YES;
    [self.privacyLabel addGestureRecognizer:privacyTapGesture];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)agreementLabelTapped:(UITapGestureRecognizer *)gesture {
    NSLog('用户协议被点击');
    // 在这里处理用户协议被点击的逻辑
}

- (void)privacyLabelTapped:(UITapGestureRecognizer *)gesture {
    NSLog('隐私协议被点击');
    // 在这里处理隐私协议被点击的逻辑
}

@end

在这段代码中,我们首先创建了两个UILabel(agreementLabel和privacyLabel),并设置了它们的文本样式。然后,我们为每个UILabel添加了一个点击手势,当用户点击标签时,会调用相应的点击事件处理方法(agreementLabelTapped和privacyLabelTapped)。你可以根据自己的需求在这些方法中添加具体的逻辑。

iOS开发: 使用UILabel实现可点击的“同意用户协议”和“隐私协议”文字(含详细代码)

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

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