问题描述
我的目标是创建一个 SwiftUI 视图,它接受一个字符串并自动将该文本格式化为文本视图。需要格式化的字符串部分使用正则表达式找到,然后作为 Range
The Complex info field is required when Type is complex.
我收到错误 struct AttributedText: View {
@State var text: String
var body: some View {
AttributedTextView(text: text)
}
@ViewBuilder
private func AttributedTextView(text: String) -> some View {
if let range = text.range(of: "[0-9]+d[0-9]+",options: .regularExpression) {
//The unattributed text
Text(text[text.startIndex..<range.lowerBound]) +
//Append the attributed text
Text(text[range]).bold() +
//Search for additional instances of text that needs attribution
AttributedTextView(text: String(text[range.upperBound..<text.endIndex]))
} else {
//If the searched text is not found,add the rest of the string to the end
Text(text)
}
}
,建议的解决方法是将递归行更新为 Cannot convert value of type 'some View' to expected argument type 'Text'
。我应用了这个修复,但仍然看到相同的编译器错误和相同的建议修复。
我尝试过的一些解决方法:
- 将返回类型从
AttributedTextView(text: String(text[range.upperBound..<text.endIndex])) as! Text
更改为some View
。这会产生不同的错误Text
。我没有真正深入探讨这一点,因为返回值依赖于该条件确实是有道理的。 - 返回组而不是文本,这会导致整个 SwiftUI 文件中出现其他错误
这些解决方案都没有感觉非常“Swifty”。还有什么方法可以解决这个问题?我在 SwiftUI 中误解了什么吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)