Alex
Alex

Reputation: 287

How to extract Hashtags from text using SwiftUI?

Is there any way to find Hashtags from a text with SwiftUI? This is how my try looks like:

calling the function like this : Text(convert(msg.findMentionText().joined(separator: " "), string: msg)).padding(.top, 8) . But it does not work at all.

My goal something like this: enter image description here

   extension String {
    func findMentionText() -> [String] {
        var arr_hasStrings:[String] = []
        let regex = try? NSRegularExpression(pattern: "(#[a-zA-Z0-9_\\p{Arabic}\\p{N}]*)", options: [])
        if let matches = regex?.matches(in: self, options:[], range:NSMakeRange(0, self.count)) {
            for match in matches {
                arr_hasStrings.append(NSString(string: self).substring(with: NSRange(location:match.range.location, length: match.range.length )))
            }
        }
        return arr_hasStrings
    }
}
func convert(_ hashElements:[String], string: String) -> NSAttributedString {

    let hasAttribute = [NSAttributedString.Key.foregroundColor: UIColor.orange]

    let normalAttribute = [NSAttributedString.Key.foregroundColor: UIColor.black]

    let mainAttributedString = NSMutableAttributedString(string: string, attributes: normalAttribute)

    let txtViewReviewText = string as NSString

    hashElements.forEach { if string.contains($0) {
        mainAttributedString.addAttributes(hasAttribute, range: txtViewReviewText.range(of: $0))
        }
    }
    return mainAttributedString
}

Upvotes: 0

Views: 840

Answers (1)

LuLuGaGa
LuLuGaGa

Reputation: 14418

You need to initailize Text() with a String, but instead you are attempting to initialize it with an Array of String.

You could either just display the first one if the array is not empty:

msg.findMentionText().first.map { Text($0) }

Or you could join the elements array into a single String:

 Text(msg.findMentionText().joined(separator: " "))

Upvotes: 2

Related Questions