在 iOS 开发中,可以通过设置 UILabel 的属性来添加链接,并实现点击跳转功能。下面是一个示例的 Objective-C 代码:

// 首先,导入头文件
#import <UIKit/UIKit.h>

// 创建一个自定义的 UILabel 子类
@interface LinkLabel : UILabel

@end

@implementation LinkLabel

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取点击的位置
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    
    // 判断点击的位置是否在链接范围内
    NSAttributedString *attributedText = self.attributedText;
    if (attributedText.length > 0) {
        NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
        NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.bounds.size];
        NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedText];
        
        [layoutManager addTextContainer:textContainer];
        [textStorage addLayoutManager:layoutManager];
        
        NSRange textRange = NSMakeRange(0, attributedText.length);
        CGRect textBoundingBox = [layoutManager usedRectForTextContainer:textContainer];
        
        // 将点击的位置转换为文本容器中的坐标系
        CGPoint textLocation = CGPointMake(location.x - CGRectGetMinX(textBoundingBox), location.y - CGRectGetMinY(textBoundingBox));
        
        NSUInteger characterIndex = [layoutManager characterIndexForPoint:textLocation inTextContainer:textContainer fractionOfDistanceBetweenInsertionPoints:NULL];
        
        // 判断点击的位置是否在链接的范围内
        for (NSDictionary *link in self.linkRanges) {
            NSRange linkRange = [link['range'] rangeValue];
            if (characterIndex >= linkRange.location && characterIndex < linkRange.location + linkRange.length) {
                // 处理点击事件,例如跳转到指定页面
                NSString *urlString = link['url'];
                NSURL *url = [NSURL URLWithString:urlString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
                break;
            }
        }
    }
}

@end

在上面的代码中,我们创建了一个自定义的 UILabel 子类 LinkLabel,并重写了 touchesEnded:withEvent: 方法来处理点击事件。在点击事件中,我们使用 NSLayoutManagerNSTextContainerNSTextStorage 来计算点击的位置是否在链接范围内,并执行相应的操作。

在使用 LinkLabel 时,需要设置其 attributedText 属性来显示带有链接的文本,并使用 linkRanges 属性来保存链接的范围和 URL。例如:

LinkLabel *label = [[LinkLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
label.numberOfLines = 0;

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

// 添加链接
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
[attributedText addAttributes:linkAttributes range:NSMakeRange(4, 4)];

// 设置链接的 URL
[label setLinkRanges:@[@{@'range': [NSValue valueWithRange:NSMakeRange(4, 4)], @'url': @'http://www.baidu.com'}]];

label.attributedText = attributedText;

在上面的代码中,我们创建了一个 LinkLabel 实例,并设置其 attributedText 属性来显示带有链接的文本。通过 setLinkRanges: 方法,我们设置了链接的范围和 URL。

当用户点击该标签时,会触发 touchesEnded:withEvent: 方法,在该方法中判断点击的位置是否在链接范围内,并执行相应的操作,例如打开指定的 URL。


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

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