gpt4 book ai didi

ios - 在 SwiftUI 2.0 中更改应用程序图标时出现 fatal error

转载 作者:行者123 更新时间:2023-12-04 08:29:29 25 4
gpt4 key购买 nike

我正在尝试允许用户自定义应用程序图标到我的应用程序。我在 SwiftUI 1.0(旧生命周期)中找到了执行此操作的教程,并尝试使其在新生命周期中工作。我专门使用了 this tutorial .我收到 fatal error Fatal error: No ObservableObject of type IconNames found. A View.environmentObject(_:) for IconNames may be missing as an ancestor of this view.首先,我使用以下内容更新了我的 info.plist 文件

<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconName</key>
<string></string>
<key>CFBundleIconFiles</key>
<array>
<string></string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
<key>CFBundleAlternateIcons</key>
<dict>
<key>Dark</key>
<dict>
<key>CFBundleIconFiles</key>
<array/>
<key>Item 0</key>
<string>Dark</string>
</dict>
</dict>
</dict>
然后我将以下代码添加到我的设置页面(我通过内容 View 中的导航链接导航到的页面。
import SwiftUI

struct Settings: View {
@EnvironmentObject var iconSettings : IconNames

var body: some View {
Form{
Section{
Picker(selection: $iconSettings.currentIndex, label: Text("App icon")){
ForEach(0 ..< iconSettings.iconNames.count){ i in
HStack{
Text(self.iconSettings.iconNames[i] ?? "AppIcon")
Image(uiImage: UIImage(named: self.iconSettings.iconNames[i] ?? "AppIcon") ?? UIImage())
.resizable()
.renderingMode(.original)
.frame(width: 50, height: 50, alignment: .leading)
}
}
}.onReceive([self.iconSettings.currentIndex].publisher.first()) { (value) in

let index = self.iconSettings.iconNames.firstIndex(of: UIApplication.shared.alternateIconName) ?? 0

if index != value{

UIApplication.shared.setAlternateIconName(self.iconSettings.iconNames[value]){ error in
if let error = error {
print(error.localizedDescription)
} else {
print("Success!")
}
}
}
}
}
}
.navigationTitle("Settings")
}
}


class IconNames: ObservableObject {
var iconNames: [String?] = [nil]
@Published var currentIndex = 0
init() {
getAlternateIcons()

if let currentIcon = UIApplication.shared.alternateIconName{
self.currentIndex = iconNames.firstIndex(of: currentIcon) ?? 0
}
}
func getAlternateIcons() {
if let icons = Bundle.main.object(forInfoDictionaryKey: "CFBundleIcons") as? [String : Any], let alternateIcons = icons["CFBundleAlternateIcons"] as? [String: Any] {

for (_, value) in alternateIcons{

guard let iconList = value as? Dictionary<String,Any> else{return}
guard let iconFiles = iconList["CFBundleIconFiles"] as? [String]
else{return}

guard let icon = iconFiles.first else{return}
iconNames.append(icon)

}
}
}
}

最佳答案

代替Settings您必须提供的 View 创建environmentObject , 像

Settings().environmentObject(IconNames())

关于ios - 在 SwiftUI 2.0 中更改应用程序图标时出现 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65093726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com