swift写一个字符串高亮效果,高亮可以点击

2023-04-05  本文已影响0人  笙笔记

以下是一个使用 Swift 实现的字符串高亮效果,高亮部分可以点击的示例:

func highlightString(originalString: String, highlightString: String, target: AnyObject?, action: Selector?) -> NSAttributedString {
    let attributedString = NSMutableAttributedString(string: originalString)
    let range = NSString(string: originalString).range(of: highlightString, options: .caseInsensitive)
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
    if target != nil && action != nil {
        let tapGesture = UITapGestureRecognizer(target: target, action: action)
        attributedString.addAttribute(NSAttributedString.Key.link, value: target!, range: range)
        attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
        attributedString.addAttribute(NSAttributedString.Key.underlineColor, value: UIColor.blue, range: range)
        attributedString.addAttribute(NSAttributedString.Key.gestureRecognizers, value: [tapGesture], range: range)
    }
    return attributedString
}

这个函数接受四个参数,一个是原始字符串,另一个是要高亮的字符串,第三个参数是目标对象,最后一个参数是要执行的方法。它返回一个 NSAttributedString 对象,其中高亮字符串已经使用红色文本颜色进行了标记,并且可以被点击。

要使用这个函数,只需要传入原始字符串、要高亮的字符串、目标对象和要执行的方法即可。例如

@objc func handleTap(_ gesture: UITapGestureRecognizer) {
    guard let attributedString = gesture.view as? NSAttributedString else {
        return
    }
    let range = (attributedString.string as NSString).range(of: highlightString, options: .caseInsensitive)
    // 执行一些操作,例如显示一个提示框或者跳转到其他页面
}

在这个示例中,handleTap 方法首先将被点击的字符串转换为 NSAttributedString 对象,然后获取高亮字符串的范围,最后执行一些操作,例如显示一个提示框或者跳转到其他页面。

上一篇 下一篇

猜你喜欢

热点阅读