I want to implement text that can detect links and click.
Everything was perfect, but I found one strange thing. When the Text with linelimit() and long string and the latter part is omitted, if there is a newLine before that, ellipsis disappears.
Without newLine, it works fine.
import SwiftUI
struct ContentView: View {
let text: String = "test test www.google.com \n ddfk \n jdkfjdfd \n"
var body: some View {
VStack {
Text(linkDetectableText(text: text))
.truncationMode(.tail)
.lineLimit(2)
.environment(\.openURL, OpenURLAction { url in
print(url)
return .handled
})
.onTapGesture {
print("Tapped")
}
}
.padding()
}
func linkDetectableText(text: String) -> AttributedString {
let mutableString = NSMutableAttributedString()
let normalText = NSAttributedString(string: text)
mutableString.append(normalText)
var urlAttributes: [NSMutableAttributedString.Key: Any] = [
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(
in: text,
options: [],
range: NSRange(location: 0, length: text.count)
)
for m in matches {
if let url = m.url {
urlAttributes[.attachment] = url
mutableString.setAttributes(urlAttributes, range: m.range)
//If you remove this code, the ellipsis appears normally, but url is not clicked.
mutableString.addAttribute(NSAttributedString.Key.link, value: url, range: m.range)
}
}
} catch {
print(error)
}
return AttributedString(mutableString)
}
}
As a result of removing url attr from the above code
The result of removing newLine from text in the code above and writing it long
I tried adding a linebreak of paragraphStyle to the NSAttributedString, and I also tried the AttributedString instead of the NSAttachedString. I tried using AttributedString only on the link Text by dividing the Text also did not work.
This strage behavior occurred when the link attribute added to AttributedString. Is this a bug? Is there any way in SwiftUI that can fix this?