Created
February 16, 2020 08:43
-
-
Save alexito4/42488bfcf5385467c758633e389eb62f to your computer and use it in GitHub Desktop.
SwiftUI Mac broken foreach ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Combine | |
struct Object: Identifiable { | |
var id: String { name } | |
let name: String | |
} | |
final class Data: ObservableObject { | |
@Published var selected: [Object] | |
@Published var all: [Object] | |
init(selected: [Object], all: [Object]) { | |
self.selected = selected | |
self.all = all | |
} | |
var notSelected: [Object] { | |
all.filter({ o in !selected.contains(where: { $0.id == o.id }) }) | |
} | |
} | |
struct ContentView: View { | |
@ObservedObject var data: Data | |
var body: some View { | |
List { | |
Text("Selected \(self.data.selected.count)") | |
.font(.title) | |
ForEach(self.data.selected) { obj in | |
Row(text: obj.name, circle: true, buttonText: "Remove", action: { | |
self.data.selected.removeAll { | |
$0.id == obj.id | |
} | |
}) | |
} | |
Text("The rest \(self.data.notSelected.count)") | |
.font(.title) | |
ForEach(self.data.notSelected) { obj in | |
Row(text: obj.name, circle: false, buttonText: "Add", action: { self.data.selected.append(obj) }) | |
} | |
} | |
.frame(width: 400, height: 500) | |
} | |
} | |
struct Row: View { | |
let text: String | |
let circle: Bool | |
let buttonText: String | |
let action: () -> () | |
var body: some View { | |
HStack { | |
if circle { | |
Circle() | |
.fill(Color.red) | |
.frame(width: 10, height: 10) | |
} | |
Text(text) | |
Button(action: action) { | |
Text(buttonText) | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView(data: Data( | |
selected: [ | |
Object(name: "Selected") | |
], | |
all: [ | |
Object(name: "A"), | |
Object(name: "B"), | |
Object(name: "C"), | |
Object(name: "D"), | |
] | |
)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment