iOS开发:UILabel 实现用户协议和隐私协议文字变蓝可点击
在 iOS 开发中,可以使用 UILabel 和 UITapGestureRecognizer 来实现同意用户协议和隐私协议的文字变蓝色可点击的效果。下面是详细的 Objective-C 代码示例:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UILabel *userAgreementLabel;
@property (nonatomic, strong) UILabel *privacyPolicyLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.userAgreementLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 30)];
self.userAgreementLabel.userInteractionEnabled = YES;
self.userAgreementLabel.textColor = [UIColor blackColor];
self.userAgreementLabel.text = '点击同意用户协议';
[self.view addSubview:self.userAgreementLabel];
self.privacyPolicyLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 150, 200, 30)];
self.privacyPolicyLabel.userInteractionEnabled = YES;
self.privacyPolicyLabel.textColor = [UIColor blackColor];
self.privacyPolicyLabel.text = '点击同意隐私协议';
[self.view addSubview:self.privacyPolicyLabel];
UITapGestureRecognizer *tapUserAgreementGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapUserAgreement:)];
[self.userAgreementLabel addGestureRecognizer:tapUserAgreementGesture];
UITapGestureRecognizer *tapPrivacyPolicyGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPrivacyPolicy:)];
[self.privacyPolicyLabel addGestureRecognizer:tapPrivacyPolicyGesture];
}
- (void)tapUserAgreement:(UITapGestureRecognizer *)gesture {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.userAgreementLabel.text];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(2, self.userAgreementLabel.text.length - 8)];
self.userAgreementLabel.attributedText = attributedString;
// 在这里添加点击同意用户协议后的逻辑处理代码
}
- (void)tapPrivacyPolicy:(UITapGestureRecognizer *)gesture {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.privacyPolicyLabel.text];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(2, self.privacyPolicyLabel.text.length - 8)];
self.privacyPolicyLabel.attributedText = attributedString;
// 在这里添加点击同意隐私协议后的逻辑处理代码
}
@end
上述代码中,首先创建了两个 UILabel 对象分别表示用户协议和隐私协议的文本。然后设置 UILabel 的一些属性,如 frame、userInteractionEnabled 和 text 等。接着创建了两个 UITapGestureRecognizer 对象,并分别为两个 UILabel 对象添加了手势识别器。在点击手势回调方法中,使用 NSMutableAttributedString 将点击的文字部分变为蓝色,并更新 UILabel 的 attributedText 属性,以达到文字变蓝色的效果。最后,可以在回调方法中添加点击同意协议后的逻辑处理代码。
原文地址: https://www.cveoy.top/t/topic/XH8 著作权归作者所有。请勿转载和采集!