【发布时间】:2021-07-31 09:15:23
【问题描述】:
这是我的 macOS 应用程序中的 URL 地址栏,可以正常使用此 TextField:
@State private var text = ""
@State private var site = "www.google.com/" //stored as two separate values so that WebKit isn't trying to continuously load a URL with every single keystroke. The "site" property is only updated once the user presses the return key.
var body: some View {
let webView = WebView(site: $site, text: $text)
TextField("Enter a URL", text: $text, onCommit: {
guard !text.isEmpty else {return}
site = text
})
webView //To display the loaded web page
}
..但是在实现trim function 后,当用户将 URL 复制并粘贴到地址栏上时删除“https://”,WebKit 现在尝试在每次击键时不断加载 URL,我的应用程序停止工作。
@State private var text = ""
@State private var site = "www.google.com/"
var body: some View {
let webView = WebView(site: $site, text: $text)
TextField("Enter a URL", text: Binding(
get: { text },
set: { newValue in
if trim(newValue).starts(with: "https://") {
text = String(trim(newValue).dropFirst(8))
} else {
text = newValue
}
}), onCommit: {
guard !text.isEmpty else {return}
site = text
})
webView //To display the loaded web page
}
func trim(_ str: String) -> String {
return str.trimmingCharacters(in: .whitespacesAndNewlines)
}
网页视图
struct WebView: NSViewRepresentable {
@Binding var site: String
private var webView: WKWebView
init(site: Binding<String>, text: Binding<String>) {
self.webView = WKWebView()
_site = site //
}
func makeNSView(context: Context) -> WKWebView {
return webView
}
func updateNSView(_ nsView: WKWebView, context: Context) {
nsView.load(URLRequest(url: (URL(string: "https://" + site) ?? Bundle.main.url(forResource: "URLError", withExtension: "pdf")!)))
}
【问题讨论】:
-
向我们展示 WebKit 尝试不断加载 url 的代码。
-
当事情变得更复杂时,考虑使用 ViewModel 来处理整个数据相关的方面和逻辑,并让视图只呈现值。
-
@workingdog 添加了要发布的代码
-
我看到了您发布的错误消息,但我没有看到 WebKit 尝试连续加载 url 的代码。我怀疑您为此使用“文本”,而您应该使用“站点”
-
@workingdog 我已经添加了我所有的代码。 WebView 与问题中的第一个文本字段完美配合。只有在尝试使用您之前在这篇文章中的第二个文本字段中向我展示的修剪功能之后,才会出现问题。