用 20+ 行 JavaScript 代码,短暂“变身”iOS 程序员

摘要:你有没有尝试过在 iOS 中创建小部件,感受一把身为 iOS 程序员的快乐?本文作者将用二十几行 JavaScript 代码教你构建一个 iOS 小部件,据他所说,这“一点都不难”。

原文链

接:https://stackonfire.com/feel-yourself-ios-developer-with-20-lines-of-javascript声明:本文为 CSDN 翻译,未经授权,禁止转载。

作者 | Dimitri Ivashchuk

译者 | 弯月

出品 | CSDN(ID:CSDNnews)

在这篇入门指南中,我们将构建如下软件,实际所需编写的 JavaScript 代码非常少。

这个软件的创意来源有两个:

1.有人使用这个小部件来显示收入。

2.频繁检查 GitHub 代码库的星星数量很麻烦。

我发现,构建 iOS 小部件一点都不难,只要有合适的工具,再加上非常基础的 JavaScript 知识即可!

项目简介

这个项目是一个 iOS 小部件,用来显示 GitHub 代码库的星星数量。这里我通过自己的一个开源项目为例进行说明。我们将采用 Scriptable,这个工具可以通过 JavaScript 生成漂亮的小部件,就像上图一样。

代码

// Request// Nothing special here, just an async request function GitHub open APIasync function getGithubData {const url = "https://api.github.com/repos/lost-pixel/lost-pixel";const request = new Request(url);const response = await request.loadJSON;return response;}//UI// Function that defines the element of the widgetasync function createWidget {// Fetching data with the function we prepared beforeconst githubData = await getGithubData;// Create new wdiget & set black background colorlet listwidget = new ListWidget;listwidget.backgroundColor = new Color("#000000");// Create heading and style it properlylet heading = listwidget.addText("⭐ Lost Pixel ⭐");heading.centerAlignText;heading.font = Font.lightSystemFont(25);heading.textColor = new Color("#fff");// Add spacer between elementslistwidget.addSpacer(15);// Create the stars display and style it properly. We use the data from API herelet stars = listwidget.addText(githubData.stargazers_count);stars.centerAlignText;stars.font = Font.semiboldSystemFont(20);stars.textColor = new Color("#ffffff");return listWidget;}// Execute createWidget function that returns us the widgetlet widget = await createWidget;// Show the widget when added to IOS homescreenif (config.runsInWidget) {Script.setWidget(widget);} else {widget.presentMedium;}// finish the execution of the scriptScript.complete;

显示小部件

1.在 iOS 设备上安装 Scriptable for iOS;

2.点击 + 按钮创建一个新的脚本。

3. 将上面的代码粘贴到空白输入处。

4. 保存,这样就完成了!

5. 最后一步,只需将这个小部件添加到主屏幕即可:通过 Scriptable 小部件,将刚刚建好的小部件添加到主屏幕。

好了,恭喜你完成了!

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...