自制猜八卦小程序SwiftUI学习笔记三
自制猜八卦小程序
1.创建新的SwiftUI工程,随意命名工程。
2.自备八卦图片,PNG格式的,放入工程文件夹专用文件夹中。
3.在ContentView.swift中,import SwiftUI之前定义数组常量,即八卦名称,需要与图片名称对应。
4.小程序内容为随机出现三个卦象图片,然后给出挂名,需要选择正确的挂名对应的图片,并根据选择对错计算得分所以,定义以下变量。
因为BaguasName在定义时即获取常量数组随机排序(shuffled)后的值,所以常量数组不能放置在struct内。
添加背景颜色,做点修饰
预览如下(也不怎么好看,比纯白好点。自己添加了背景,SwiftUI的自动darkmode模式应该就不会自己启用了)
编写函数,检查答案以及继续游戏
正确卦象的位置在出题时已经确定,可以看定义以及reStartGame(),所以答案检查部分,只是核对传入Int的值。
加入卦象图案,三个,垂直排列
这里在图像显示的地方,使用了苹果官方用来显示图片的类,ImageStroe.shared.image,使用这个类可以方便的显示在工程中的某个文件夹中的图片,而不是必须把图片放到 Assets.xcassets 这个文件夹里。后面截图显示该类内容。
预览如图
添加Text视图显示得分。
触发警告框放在了ForEach后
使用navigationBarTitle显示卦象名,即使没有使用NavigationView依然可以是使用其title的
显示模式为.inline,则卦名不会那么大。
模拟器显示如图
SwiftUI简直了。
final class ImageStore {
typealias _ImageDictionary = [String: CGImage]
fileprivate var images: _ImageDictionary = [:]
fileprivate static var scale = 2
static var shared = ImageStore()
func image(name: String) -> Image {
let index = _guaranteeImage(name: name)
return Image(images.values[index], scale: CGFloat(ImageStore.scale), label: Text(verbatim: name))
}
static func loadImage(name: String) -> CGImage {
guard
let url = Bundle.main.url(forResource: name, withExtension: "png"),
let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil),
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)
else {
fatalError("Couldn't load image \(name).jpg from main bundle.")
}
return image
}
fileprivate func _guaranteeImage(name: String) -> _ImageDictionary.Index {
if let index = images.index(forKey: name) { return index }
images[name] = ImageStore.loadImage(name: name)
return images.index(forKey: name)!
}
}
//获取图片名字
func getPicsName() -> [String]
{
var pictures = [String]()
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items
{
if item.hasPrefix("nssl")
{
pictures.append(item)
}
}
return pictures
}