You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于ActiveLabel实现@提及文本转换与点击事件页面识别需求

解决方案:用ActiveLabel处理自定义@提及格式

嘿,我刚好有过用ActiveLabel处理这种自定义@提及格式的经验,给你分享下具体的实现步骤:

1. 解析原始字符串,提取显示文本与用户标识

首先我们需要把你的原始字符串里的@[名称](标识)格式转换成ActiveLabel能识别的结构,同时保留要显示的纯文本。可以用正则表达式来匹配并替换:

import ActiveLabel

func parseMentionString(_ originalString: String) -> (displayText: String, mentionMap: [String: String]) {
    var mentionMap = [String: String]() // 存储显示名称对应的用户标识
    let regex = try! NSRegularExpression(pattern: "@\\[([^\\]]+)\\]\\(([^\\)]+)\\)", options: [])
    let range = NSRange(originalString.startIndex..., in: originalString)
    
    // 先提取所有提及项
    regex.enumerateMatches(in: originalString, options: [], range: range) { match, _, _ in
        guard let match = match else { return }
        let nameRange = match.range(at: 1)
        let idRange = match.range(at: 2)
        if let name = originalString.substring(with: nameRange), let id = originalString.substring(with: idRange) {
            mentionMap[name] = id
        }
    }
    
    // 替换成纯显示文本
    let displayText = regex.stringByReplacingMatches(in: originalString, options: [], range: range, withTemplate: "$1")
    return (displayText, mentionMap)
}

2. 配置ActiveLabel识别提及并处理点击

接下来把解析后的文本传给ActiveLabel,并且设置自定义的提及规则,点击时根据显示名称找到对应的用户标识,跳转到对应页面:

// 假设你已经有一个ActiveLabel实例
let activeLabel = ActiveLabel()
let originalString = "@[Hema](hema_ramburuth), @[Ilesh P](ilesh.panchal), @[Lewis Murphy](lewis) how are you?"

let (displayText, mentionMap) = parseMentionString(originalString)
activeLabel.text = displayText

// 配置自定义提及类型
activeLabel.enabledTypes = [.custom]
activeLabel.customize { label in
    label.customColor = .blue // 设置提及文本的颜色
    label.customSelectedColor = .darkGray // 点击后的颜色
    
    // 识别所有在mentionMap里的名称作为提及项
    label.customPattern = try! NSRegularExpression(pattern: "\\b(" + mentionMap.keys.joined(separator: "|") + ")\\b", options: .caseInsensitive)
}

// 设置点击回调
activeLabel.handleCustomTap = { matchedString in
    guard let userId = mentionMap[matchedString] else { return }
    // 这里根据userId跳转到对应的用户页面
    print("点击了用户:\(matchedString),用户ID:\(userId)")
    // 比如:navigateToUserProfile(with: userId)
}

这样处理后,ActiveLabel会显示成Hema, Ilesh P, Lewis Murphy how are you?,并且点击每个名称时,能拿到对应的用户标识,进而跳转到对应的页面。

如果你的字符串里包含特殊字符,可能需要微调正则表达式的匹配规则,确保能正确捕获所有提及项。

内容的提问来源于stack exchange,提问作者Ilesh Panchal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:41:23