javascript - 如何将 js 或任何函数的结果返回到 iPhone 的屏幕?通过内容视图
问题描述
// ContentView.swift
// Shared
import Foundation
import SwiftUI
import JavaScriptCore
class cube {
var result: String
func do_js(text: String) -> String {
let jsSource = "var testFunct = function(message) { return \"Test Message: \" + message;}"
var context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
var result = testFunction?.call(withArguments: [text]).toString()
return result!
}
}
struct ContentView: View {
cube().do_js(text: "Hello world") // Starts forom here
var show_text = lol().result
var body: some View {
Text(show_text)
.font(.body)
.fontWeight(.black)
.foregroundColor(Color.red)
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
(对不起,我是初学者,甚至不是从 js 开始,而是从 python 开始!所以这对我来说是非常新的。但是从 python 对我来说,js 更容易理解。)
解决方案
这是最简单的版本。在这个版本中,它基本上使用你的原始模式doJS
返回一个值。这个版本的缺点是doJS
每次视图渲染时都会被调用。
class Cube {
func doJS(text: String) -> String? {
let jsSource = "var testFunct = function(message) { return \"Test Message: \" + message;}"
let context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
return testFunction?.call(withArguments: [text]).toString()
}
}
struct ContentView: View {
var body: some View {
Text(Cube().doJS(text: "Hello, world!") ?? "No result")
.font(.body)
.fontWeight(.black)
.foregroundColor(Color.red)
.padding()
}
}
这是一个略有不同的版本。在这个版本中,Cube
是一个ObservableObject
带有@Published
存储结果的值。它只会被调用一次。onAppear
class Cube : ObservableObject {
@Published var result : String?
func doJS(text: String) {
let jsSource = "var testFunct = function(message) { return \"Test Message: \" + message;}"
let context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
result = testFunction?.call(withArguments: [text]).toString()
}
}
struct ContentView: View {
@StateObject var cube = Cube()
var body: some View {
Text(cube.result ?? "No result")
.font(.body)
.fontWeight(.black)
.foregroundColor(Color.red)
.padding()
.onAppear {
cube.doJS(text: "Hello, world!")
}
}
}
推荐阅读
- javascript - 在特定列表项之后添加元素
- javascript - How do I change the div size by clicking multiple button?
- python - 如何绘制范围数据的散点图
- mysql - mysql-data 文件夹中的巨大#sql-xxxx-xxxx.ibd 文件
- airflow - 每月 DAG 计划每天凌晨 2:30 运行
- jdbc - 找不到适合 jdbc:firebirdsql://localhost:3050 的驱动程序
- cuda - CUDA:将设备函数作为参数传递给全局函数
- javascript - 如何同时从数组和列表中删除值?
- sql - 获取除前两列之外的所有其他列的总和
- android - 将 com.google.android.gms:play-services-ads:19.4.0 更新到 20.1.0 仍然有一些不推荐使用的方法被 CustomEventBannerListener 期待