SwiftUI开发:拼接变量到图片名后图片消失问题求助
SwiftUI老虎机图片不显示问题解决办法
你的问题核心是图片命名和代码逻辑不匹配:当前代码里每个插槽固定用了不同的前缀(第一个插槽永远是apple开头,第二个永远是cherry开头),但随机数生成后,比如slot1变成2,你加载的是apple2,但你的资源里大概率只有apple、cherry、star这类基础名称,或者是apple1、cherry1、star1,没有apple2、apple3这类文件,所以系统找不到图片,自然就显示空白了。
给你两种直接可行的解决办法:
办法一:统一图片命名,对齐随机逻辑
把所有老虎机图片统一命名为带编号的格式,比如fruit1(对应苹果)、fruit2(对应樱桃)、fruit3(对应星星),然后修改代码让每个插槽都从这些编号图片里随机:
import SwiftUI struct ContentView: View { @State var userCredits = 1000 @State var slot1 = 1 @State var slot2 = 1 @State var slot3 = 1 var body: some View { VStack { Text("SwiftUI Slot!") .font(.system(size: 38)) .fontWeight(.medium) Spacer() Text("Credits: \(userCredits)") Spacer() HStack{ // 统一用fruit前缀,配合随机编号 Image("fruit\(slot1)") .resizable() .aspectRatio(contentMode: .fit) Image("fruit\(slot2)") .resizable() .aspectRatio(contentMode: .fit) Image("fruit\(slot3)") .resizable() .aspectRatio(contentMode: .fit) } Spacer() Button("Spin") { slot1 = Int.random(in: 1...3) slot2 = Int.random(in: 1...3) slot3 = Int.random(in: 1...3) if slot1 == slot2 && slot2 == slot3{ userCredits += 15 } else { userCredits -= 5 } } } } }
注意:必须确保Assets.xcassets里存在fruit1、fruit2、fruit3这三个图片资源,名称完全一致(大小写敏感)。
办法二:用数组管理图片名称(更灵活)
如果不想改图片命名,可以直接把所有图片名放进数组,通过随机索引来获取图片,逻辑更清晰:
import SwiftUI struct ContentView: View { @State var userCredits = 1000 // 用数组存所有图片名称,和Assets里的名称一致 let slotImageNames = ["apple", "cherry", "star"] @State var slot1Index = 0 @State var slot2Index = 0 @State var slot3Index = 0 var body: some View { VStack { Text("SwiftUI Slot!") .font(.system(size: 38)) .fontWeight(.medium) Spacer() Text("Credits: \(userCredits)") Spacer() HStack{ Image(slotImageNames[slot1Index]) .resizable() .aspectRatio(contentMode: .fit) Image(slotImageNames[slot2Index]) .resizable() .aspectRatio(contentMode: .fit) Image(slotImageNames[slot3Index]) .resizable() .aspectRatio(contentMode: .fit) } Spacer() Button("Spin") { // 随机生成数组索引(0到2,对应三个图片) slot1Index = Int.random(in: 0..<slotImageNames.count) slot2Index = Int.random(in: 0..<slotImageNames.count) slot3Index = Int.random(in: 0..<slotImageNames.count) // 判断三个图片是否相同 let image1 = slotImageNames[slot1Index] let image2 = slotImageNames[slot2Index] let image3 = slotImageNames[slot3Index] if image1 == image2 && image2 == image3 { userCredits += 15 } else { userCredits -= 5 } } } } }
这种方法不需要改图片名,只要保证slotImageNames里的字符串和Assets中的图片名称完全匹配即可,扩展性也更强——以后加新图片直接往数组里加就行。
最后额外检查:所有图片都要正确导入到Xcode项目中,并且在Assets.xcassets里没有拼写错误,Swift对字符串大小写敏感,比如Apple和apple会被当成两个不同的资源。
内容的提问来源于stack exchange,提问作者H4R3L
相关产品推荐
相关产品推荐

