iOS 开发:UILabel 实现 同意用户协议 和 隐私协议 点击变色
下面是使用 UILabel 实现同意用户协议和隐私协议,使文字变蓝色并可点击的 OC 代码示例:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UILabel *agreementLabel;
@property (nonatomic, strong) UILabel *privacyLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建 UILabel 对象
self.agreementLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 30)];
self.agreementLabel.userInteractionEnabled = YES;
[self.view addSubview:self.agreementLabel];
self.privacyLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 150, 200, 30)];
self.privacyLabel.userInteractionEnabled = YES;
[self.view addSubview:self.privacyLabel];
// 设置 UILabel 的文本内容
NSString *agreementText = '同意用户协议';
NSMutableAttributedString *agreementAttributedString = [[NSMutableAttributedString alloc] initWithString:agreementText];
NSString *privacyText = '隐私协议';
NSMutableAttributedString *privacyAttributedString = [[NSMutableAttributedString alloc] initWithString:privacyText];
// 设置文本的属性
[agreementAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, agreementText.length)];
[privacyAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, privacyText.length)];
// 将属性文本设置给 UILabel
self.agreementLabel.attributedText = agreementAttributedString;
self.privacyLabel.attributedText = privacyAttributedString;
// 添加点击手势
UITapGestureRecognizer *agreementTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(agreementLabelTapped)];
[self.agreementLabel addGestureRecognizer:agreementTapGesture];
UITapGestureRecognizer *privacyTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(privacyLabelTapped)];
[self.privacyLabel addGestureRecognizer:privacyTapGesture];
}
- (void)agreementLabelTapped {
NSLog('用户协议被点击');
// 在此处处理同意用户协议的逻辑
}
- (void)privacyLabelTapped {
NSLog('隐私协议被点击');
// 在此处处理隐私协议的逻辑
}
@end
在上述代码中,首先创建了两个 UILabel 对象,分别是 agreementLabel 和 privacyLabel,并设置了它们的 frame 和 userInteractionEnabled 属性。
接着,创建了两个 NSMutableAttributedString 对象,分别用于设置同意用户协议和隐私协议的文本。然后使用 addAttribute:value:range: 方法将文本的颜色属性设置为蓝色。
最后,将 NSMutableAttributedString 对象设置给对应的 UILabel,并添加了点击手势,分别对应用户协议和隐私协议的点击事件。在点击事件的处理方法中,可以处理相应的逻辑。
原文地址: https://www.cveoy.top/t/topic/XKR 著作权归作者所有。请勿转载和采集!