首页 > 解决方案 > 如何将 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 更容易理解。)

在此处输入图像描述

标签: javascriptswiftxcodeswiftui

解决方案


这是最简单的版本。在这个版本中,它基本上使用你的原始模式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!")
            }
    }
}

推荐阅读