Код: Выделить всё
import SwiftUI
import Kingfisher
struct CityView: View {
@EnvironmentObject private var cityViewModel: CityViewModel
@Binding var city: City
var body: some View {
NavigationLink(destination: CityDetailView(cityId: city.id)) {
VStack {
KFImage(URL(string: city.photoUrl ?? ""))
.resizable()
.background(Color.white)
Text(city.name)
}
}
}
}
Сейчас у меня есть две разные страницы:
- Страница со списком случайных городов
- Страница профиля со списком городов, сохраненных пользователем
Код: Выделить всё
class CityViewModel: ObservableObject {
let cityService: CityServiceProtocol
@Published var cities: [City] = []
func fetchPhoto(cityId: Int) async {
do {
let data = try await cityService.getPhoto(cityId: cityId)
guard let photoUrl = data.data?.photoUrl else { return }
// Update the image url
if let index = self.cities.firstIndex(where: { $0.id == cityId }) {
self.cities[index].photoUrl = photoUrl
}
} catch {
print("Failed")
}
}
}
Для на странице профиля, на которой отображается список городов, сохраненных пользователем, у меня есть следующая модель представления:
Код: Выделить всё
class ProfileViewModel: ObservableObject {
let profileService: ProfileServiceProtocol
@Published var savedCities: [City] = []
// excluded function that fetches saved cities from the api
}
Если я хочу сохранить эту структуру использования двух моделей представления, придется ли мне копировать функцию fetchPhoto() из CityViewModel в ProfileViewModel, или можно ли иметь одну функцию это обновляет обе модели представления?
Подробнее здесь: https://stackoverflow.com/questions/792 ... iew-models