gpt4 book ai didi

swift - 如何在 SwiftUI 中用图像替换占位符文本?

转载 作者:行者123 更新时间:2023-12-05 09:01:15 24 4
gpt4 key购买 nike

我有一个字符串 "Hello {world}"我需要将其替换为 "Hello 🌍" .占位符的位置最后不固定。我可能有不止一个占位符。

我正在使用 SwiftUI 并尝试使用它来实现

Text("Hello {world}".replacingOccurrences(of: "{world}", with: "\(Image(systemName: "globe"))"))

但很快发现这是行不通的,并展示了这个 Hello Image(provider: SwiftUI.ImageProviderBox<SwiftUI.Image.(unknown context at $1ba606db0).NamedImageProvider>)

因为这行得通

Text(LocalizedStringKey("Hello \(Image(systemName: "globe"))"))

我假设我需要通过 LocalizedStringKey进入Text我再次尝试了

Text(LocalizedStringKey("Hello {world}".replacingOccurrences(of: "{world}", with: "\(Image(systemName: "globe"))")))
Text(LocalizedStringKey("Hello" + "\(Image(systemName: "globe"))")) //this doesn't work either

但出现了类似的问题 SwiftUI.Text.Storage.anyTextStorage(SwiftUI.(unknown context at $1ba668448).LocalizedTextStorage

我查看了 LocalizedStringKey 的 API和 LocalizedStringKey.StringInterpolation但找不到解决此问题的方法。有没有办法替换占位符字符串?

最佳答案

在查看@bewithyou 的回答后,我想到我需要将其拆分为多个子字符串并分别重新组合文本。这是我能想到的最佳解决方案:

public extension String {

func componentsKeepingSeparator(separatedBy separator: Self) -> Array<String> {

self.components(separatedBy: separator)
.flatMap { [$0, separator] }
.dropLast()
.filter { $0 != "" }
}
}

在 Playground 上,如果我要运行它,它会完美运行。

PlaygroundPage.current.setLiveView(

"Hello {world}!"
.componentsKeepingSeparator(separatedBy: "{world}")
.reduce(Text("")) { text, str in
if str == "{world}" { return text + Text("\(Image(systemName: "globe"))") }
return text + Text(str)
}
)

我确信有一个更优化的解决方案,但现在就可以了。

编辑:

因为我需要对多个占位符的支持,所以我添加了一些扩展来更全面地完成这项工作。

func componentsKeepingSeparators(separatedBy separators: [Self]) -> [String] {

var finalResult = [self]
separators.forEach { separator in

finalResult = finalResult.flatMap { strElement in

strElement.componentsKeepingSeparator(separatedBy: separator)
}
}
return finalResult
}

在 Playground 上

PlaygroundPage.current.setLiveView(
"Hello {world}{world}{world}! {wave}"
.componentsKeepingSeparators(separatedBy: ["{world}", "{wave}"])
.reduce(Text("")) { text, str in
if str == "{world}" { return text + Text("\(Image(systemName: "globe"))") }
if str == "{wave}" { return text + Text("\(Image(systemName: "hand.wave"))") }
return text + Text(str)
}
)

这个扩展有一个双循环,可能不是很有效,所以再次强调,如果有人能想到更好的解决方案,请发帖。

关于swift - 如何在 SwiftUI 中用图像替换占位符文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73742578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com