在 iOS 开发中,可以使用 NSAttributedString 来给 UILabel 的部分文字添加链接,并且可以点击跳转到指定的网页。下面是 Objective-C 代码示例:

首先,导入 WebKit 框架和创建一个 UILabel

#import <WebKit/WebKit.h>

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 30)];
label.numberOfLines = 0;
[self.view addSubview:label];

然后,创建一个带有链接的 NSAttributedString,并将其设置为 UILabel 的文本:

NSString *text = '点击这里跳转到百度';
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];

// 设置链接属性
[attributedString addAttribute:NSLinkAttributeName value:'https://www.baidu.com' range:NSMakeRange(2, 4)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(2, 4)];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(2, 4)];

// 设置文本属性
NSDictionary *attributes = @{
    NSFontAttributeName: [UIFont systemFontOfSize:14],
    NSForegroundColorAttributeName: [UIColor blackColor]
};
[attributedString addAttributes:attributes range:NSMakeRange(0, text.length)];

label.attributedText = attributedString;

最后,实现 UILabel 的点击事件,当用户点击链接时,跳转到指定的网页:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 允许 UILabel 接收点击事件
    label.userInteractionEnabled = YES;
    
    // 添加 UITapGestureRecognizer
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped:)];
    [label addGestureRecognizer:tapGestureRecognizer];
}

- (void)labelTapped:(UITapGestureRecognizer *)gestureRecognizer {
    // 获取点击的位置
    CGPoint location = [gestureRecognizer locationInView:label];
    
    // 获取点击位置的属性
    NSDictionary *attributes = [label.attributedText attributesAtIndex:location.x effectiveRange:NULL];
    
    // 检查是否包含链接属性
    NSURL *url = attributes[NSLinkAttributeName];
    if (url) {
        // 跳转到指定的网页
        WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
        [webView loadRequest:[NSURLRequest requestWithURL:url]];
        [self.view addSubview:webView];
    }
}

这样,当用户点击带有链接的部分文字时,将会跳转到指定的网页。

iOS 开发 UILabel 部分文字添加链接并跳转 - Objective-C 代码示例

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

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