javascript - 从 Swift 更新 Javascript 值

标签 javascript html ios swift

我使用了一些图形库并将网页加载到我的 Swift 项目中的 UIWebview 中。

是否可以从 Swift UIViewController 更新 HTML 文件图表 Y 轴值。

如果可能的话,请给我一些例子。

更多信息请在下面找到代码和快照。

Startup.html

<!DOCTYPE HTML>
<html>

<head>
    <script type="text/javascript">
        window.onload = function () {
            // initial values of dataPoints
            var dps = [
                       {label: "Management Wing", y: 125}   ,
                       {label: "Production Lab", y: 332},
                       {label: "Cafeteria", y: 55},
                       {label: "Library", y: 46},
                       {label: "Recreation Centre", y: 32}
                       ];

                       alert(dps.y);

                       var totalEmployees = "Total people on campus: 590";

                       var chart = new CanvasJS.Chart("chartContainer",{
                                                      theme: "theme2",
                                                      title:{
                                                      text: "People On Campus"
                                                      },
                                                      axisY: {
                                                      title: "Number of People"
                                                      },
                                                      legend:{
                                                      verticalAlign: "top",
                                                      horizontalAlign: "centre",
                                                      fontSize: 18

                                                      },
                                                      data : [{
                                                              type: "column",
                                                              showInLegend: true,
                                                              legendMarkerType: "none",             
                                                              legendText: totalEmployees,
                                                              indexLabel: "{y}",
                                                              dataPoints: dps
                                                              }]
                                                      });

                                                      // renders initial chart
                                                      chart.render();

                                                      var sum = 590;     //initial sum 

                                                      var updateInterval = 1000;  // milliseconds

                                                      var updateChart = function () {
                                                          // Selecting a random dataPoint
                                                          var dataPointIndex = Math.round(Math.random()*4);     

                                                          // generating random value
                                                          var deltaY = Math.round(2 + Math.random() *(-2-2));   

                                                          // adding random value to random dataPoint
                                                          dps[dataPointIndex].y = (dps[dataPointIndex].y + deltaY) > 0 ? dps[dataPointIndex].y + deltaY : 0 ;

                                                          // updating legend text. 
                                                          sum = sum + deltaY;
                                                          totalEmployees = "total people on campus: " + sum;            
                                                          chart.options.data[0].legendText = totalEmployees;    

                                                          chart.render();

                                                      };
                                                      // update chart after specified interval
                                                      setInterval(function(){updateChart()}, updateInterval);

        }   
    </script>

    <script type="text/javascript" src="/Users/wipro/Shiv_Suthan_M_Drive/Suthan_Drive/Apple_Dev/Projects/Swift/SwiftScript/SwiftScript/canvasjs.min.js"></script>
</head>
<body>
    <div id="chartContainer" style="height:300px; width:100%;">
    </div>
</body>

Viewcontroller.Swift

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let localfilePath = NSBundle.mainBundle().URLForResource("startup", withExtension: "html")
    let myRequest = NSURLRequest(URL: localfilePath!);
    modelWebView.loadRequest(myRequest);

    /*
    let url = NSURL (string: "https://www.sourcefreeze.com");
    let requestObj = NSURLRequest(URL: url!);
    modelWebView.loadRequest(requestObj);
    */


}

Screen Shot

所以我想从 Swift 更新 javascript 数据点(Y 轴)。

最佳答案

更新您的 html 文件,如下所示

var dps = [
    {label: "Management Wing", y: %ld},
    {label: "Production Lab", y: %ld},
    {label: "Cafeteria", y: %ld},
    {label: "Library", y: %ld},
    {label: "Recreation Centre", y: %ld}
];

现在像这样更改您的代码

let localfilePath = NSBundle.mainBundle().URLForResource("demo", withExtension: "html")
do {
    var myHTMLString = try NSString(contentsOfURL: localfilePath!, encoding: NSUTF8StringEncoding)
    myHTMLString = NSString(format: myHTMLString, 123, 25, 100, 46, 85) // Add 5 number that you want to change
    webView.loadHTMLString(myHTMLString as String, baseURL: NSBundle.mainBundle().URLForResource("", withExtension: "")) //Add your js file here
}
catch let error as NSError
{
    print("Error: \(error.description)")
}

希望这对您有帮助。

关于javascript - 从 Swift 更新 Javascript 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37827760/

相关文章:

ios - 右 UIBarButton 未显示

javascript - 为什么我们不能自己返回 timeOut 而不是创建一个新的 Promise?

javascript - 在 json 名称和 JSON.parse 中使用冒号时出现“意外标记”

javascript - 为什么使用 !0 将值设置为 true

javascript - 检查 Ionic 应用程序的网络状态

html - Doxygen:如何在所有输出格式的主页上嵌入图像?

php - 在字符串中查找 HTML 标签

ios - 下载未显示在 iTunes Connect 上?

ios - 我想在 ios 中发送带有图片上传的用户 ID

java - Jsoup 在第一个元素之后选择元素