Я новичок в Swift и пытаюсь позволить пользователю динамически менять значок приложения.
Проблема в том, что когда я теоретически меняю значок, значок меняется (так как я вижу всплывающую модель), но фактическое изображение значка не отображается, и я получаю значок как «неопределенный» значок приложения.
Все изображения имеют размер 1024 × 1024. и добавлен в ресурсы
Это мой код:
Код: Выделить всё
import SwiftUI
import Foundation
class IconViewModel: ObservableObject {
@Published var currentIconName: String? = UIApplication.shared.alternateIconName
func changeIcon(to icon: AppIcon) {
UIApplication.shared.setAlternateIconName(icon.iconName) { error in
DispatchQueue.main.async {
if let error = error {
print("Error changing app icon: \(error.localizedDescription)")
} else {
print("App icon changed successfully to!", icon.iconName)
self.currentIconName = icon.iconName
}
}
}
}
}
struct AppIcon: Identifiable {
let id = UUID()
let iconName: String?
let displayName: String
let image: Image
}
let appIcons = [
AppIcon(iconName: nil, displayName: "Default", image: Image("icon")),
AppIcon(iconName: "BlackBlue", displayName: "Blue & Black", image: Image("blueblack")),
AppIcon(iconName: "Dune", displayName: "Dune", image: Image("dune")),
AppIcon(iconName: "Elegant", displayName: "Classy", image: Image("elegant")),
AppIcon(iconName: "Minimal", displayName: "Minimal", image: Image("minimal"))
]
struct IconSelectionView: View {
@ObservedObject var viewModel: IconViewModel
var icons: [AppIcon]
let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 3) // Set the number of columns you want
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 20) {
ForEach(icons) { icon in
Button(action: {
viewModel.changeIcon(to: icon)
}) {
VStack {
icon.image
.resizable()
.scaledToFit()
.frame(width: 60, height: 60) // Set the size as needed
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(Color.blue, lineWidth: viewModel.currentIconName == icon.iconName ? 3 : 0)
)
Text(icon.displayName)
.font(.caption)
.foregroundColor(.primary)
}
.padding()
.background(Color.secondary.opacity(0.1))
.cornerRadius(12)
}
}
}
.padding()
}
}
}

Video:
video: current app icon switching problem
Источник: https://stackoverflow.com/questions/781 ... -correctly
Мобильная версия