尝试从WWDC会话重新创建基于SwiftUI的应用程序时遇到的问题

时间:2019-06-07 04:00:26

标签: swift swiftui

我正在尝试重新创建在Session 204中演示的SwiftUI项目,但是遇到了一些特殊的问题。

我是通过观看此处的会话来写这个的:https://developer.apple.com/videos/play/wwdc2019/204

这是我的代码-

ContentView.swift:

import SwiftUI
struct ContentView : View {
    @ObjectBinding var store = RoomStore()

    var body: some View {
        NavigationView {
            List {
                Section {
                    Button(action: addRoom) {
                        Text("Add Room")
                    }
                }

                Section {

                    ForEach(store.rooms) { room in //Error: Cannot convert value of type '(Room) -> RoomCell' to expected argument type '(_) -> _'
                        RoomCell(room: room)
                    }
                    .onDelete(perform: delete)
                    .onMove(perform: move)
                }
            }
            .navigationBarTitle(Text("Rooms") )
            .NavigationBarItems(trailing: EditButton())
            .listStyle(.grouped)
        }
    }

    func addRoom() {
        store.rooms.append(Room(name: "Hall 2", capacity: 2000))
    }
    func delete(at offsets: IndexSet) {
        store.rooms.remove(atOffsets: offsets) //Error: Incorrect argument label in call (have 'atOffsets:', expected 'at:')
    }
    func move(from source: IndexSet, to destination: Int) {
        store.rooms.move(fromOffsets: source, toOffset: destination) //Error: Value of type '[Room]' has no member 'move'; did you mean 'remove'?
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        Group {
            ContentView(store: RoomStore(rooms: testData))
            ContentView(store: RoomStore(rooms: testData))
            .environment(\.sizeCategory, .extraExtraExtraLarge)
            ContentView(store: RoomStore(rooms: testData))
            .environment(\.colorScheme, .dark)
            ContentView(store: RoomStore(rooms: testData))
            .environment(\.layoutDirection, .rightToLeft)
            .environment(\.locale, Locale(identifier: "ar"))
        }
    }
}
#endif
struct RoomCell : View {
    let room: Room
    var body: some View {
        return NavigationButton(destination: RoomDetail(room: room) )
        {
            Image(room.thumbnailName)
            .cornerRadius(8)
            VStack(alignment: .leading) {
                Text (room.name)
                Text ("\(room.capacity) peopje")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
        }
    }
}

Room.swift:

import SwiftUI

struct Room {
    var id = UUID()
    var name: String
    var capacity: Int
    var hasVideo: Bool = false
    var imageName: String { return name }
    var thumbnailName: String { return name + "Thumb" }

}

#if DEBUG

let testData = [
    Room(name: "Observation Deck", capacity: 6, hasVideo: true),
    Room(name: "Executive Suite", capacity: 8, hasVideo: false),
    Room(name: "Charter Jet", capacity: 16, hasVideo: true),
    Room(name: "Dungeon", capacity: 10, hasVideo: true),
    Room(name: "Panorama", capacity: 12, hasVideo: false),
    Room(name: "Oceanfront", capacity: 8, hasVideo: false),
    Room(name: "Rainbow Room", capacity: 10, hasVideo: true),
    Room(name: "Pastoral", capacity: 7, hasVideo: false),
    Room(name: "Elephant Room", capacity: 1, hasVideo: false),

]

#endif

RoomDetail.swift:

import SwiftUI
struct RoomDetail : View {
    let room: Room
    @State private var zoomed = false
    var body: some View { //Error: Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type
        ZStack(alignment: .topLeading) {
            Image(room.imageName )
                .resizable()
                .aspectRatio(contentMode: zoomed ? .fill : .fit)
                .navigationBarTitle(Text(room.name), displayMode:
                    .inline)
                .tapAction { withAnimation(.basic(duration: 2)) {
                    self.zoomed.toggle() } }
            }
            .frame(minWidth: 0, maxWidth: .infinity, minHeight:
                0, maxHeight: .infinity)
            if room.hasVideo && !zoomed {
                Image(systemName: "video. fill")
                    .font(.title)
                    .padding(.all)
                    .transition(.move(edge: .leading) )
            }
        }
}

#if DEBUG
struct RoomDetail_Previews : PreviewProvider {
    static var previews: some View {
        Group {
            NavigationView { RoomDetail(room: testData[0]) }
            NavigationView { RoomDetail(room: testData[1]) }
        }
}
}
#endif

RoomStore.swift:

import SwiftUI
import Combine

class RoomStore : BindableObject {
    var rooms: [Room] {
        didSet { didChange.send(Void()) } //Solved
    }
    init(rooms: [Room] = []) {
        self.rooms = rooms
    }
    var didChange = PassthroughSubject<Void, Never>()
}

上面的代码中以注释形式包含在上下文中的错误消息。

7 个答案:

答案 0 :(得分:8)

对于此错误: //错误:无法将类型'(Room)-> RoomCell'的值转换为预期的参数类型'(_)-> _' 像这样对您的列表模型实施可识别协议,

struct Room: Identifiable

对此: //错误:调用中的参数标签不正确(具有“ atOffsets:”,预期为“ at:”) 我认为这不是您的问题:)但是您可以使用类似的东西

guard let index = Array(offset).first else { return }
store.rooms.remove(at: index)

对于这个: //错误:类型[[Room]'的值没有成员'move';您是说“删除”吗?和以前一样,您可以使用这段代码来移动

guard let sourceIndex = Array(source).first else { return }
store.rooms.insert(roomStore.rooms.remove(at: sourceIndex), at: destination)

您可以检查完整的源代码, https://github.com/ilyadaberdil/iOS-Samples/tree/master/SwiftUI-Sample

答案 1 :(得分:2)

您尝试传递Void()吗?

class RoomStore : BindableObject {
    var rooms: [Room] {
        didSet { didChange.send(Void()) } 
    }
    init(rooms: [Room] = []) {
        self.rooms = rooms
    }
    var didChange = PassthroughSubject<Void, Never>()
}

答案 2 :(得分:1)

Xcode 11 beta 4

  

BindableObject 协议的要求现在是willChange,而不是didChange,现在应该在对象更改之前而不是更改之后发送。这项更改可以改善更改通知的合并。

class RoomStore: BindableObject {

    var rooms: [Room] {
        didSet { willChange.send() }
    }

    init(rooms: [Room] = []) {
        self.rooms = rooms
    }

    var willChange = PassthroughSubject<Void, Never>()
}

要删除和移动,请使用以下代码。

func delete(at offsets: IndexSet) {
    store.rooms.remove(atOffsets: offsets)
}

func move(from source: IndexSet, to destination: Int) {
    store.rooms.move(fromOffsets: source, toOffset: destination)
}

答案 3 :(得分:0)

要在列表中使用“房间”,必须执行“可识别”协议。我也忘记了它,并且错误消息///错误在这里:无法将类型'(Room)-> RoomCell'的值转换为预期的参数类型'(__-> _')没有帮助。

import SwiftUI

struct Room: Identifiable {
    let id = UUID() 
    ...
}

答案 4 :(得分:0)

对于删除和移动,您可以使用类似以下的内容:

func delete(at offsets: IndexSet) {
    offsets.sorted { $0 > $1 }.forEach { store.rooms.remove(at: $0) }
}

func move(from source: IndexSet, to destination: Int) {
    source.sorted { $0 > $1 }.forEach { store.rooms.insert(store.rooms.remove(at: $0), at: destination) }
}

答案 5 :(得分:0)

Rooms必须为@Published

class RoomStore: ObservableObject {
    @Published var rooms: [Room] {
        didSet {
            willChange.send()
        }
    }

    init(rooms: [Room] = []) {
        self.rooms = rooms
    }

   var willChange = PassthroughSubject<Void, Never>()
}

答案 6 :(得分:-1)

根据https://developer.apple.com/tutorials/swiftui/handling-user-input第4节第2步,PassthroughSubject应该采用您要绑定的类的类型,而不是Void。因此,这似乎更加正确(并且可行)。

var didChange = PassthroughSubject<RoomStore, Never>()

对于delete和move函数,由于Swift 5.1数组既没有move也没有remove(atOffsets :)方法,所以我只能假设它们忘记删除一些自定义的Array扩展。我在Swift Evolution上也找不到这些功能。

希望他们只是忘了告诉我们他们将在以后的版本中发布。

:) Teo