SwiftUI CoreData - How to update the fetch request and the list - core-data

I am creating an application in SwiftUI using CoreData and I have a problem. In application you can add song to favorites and it will be added to list (FavoriteSongsView). Until the song is added to favorites everything is fine. In DetailView I click the button and the "heart.fill" icon and the song is added to the list. However, if I click on the icon again to un-favorite the song, it does not disappear from the list. I fought with it a little bit but without any effect. Could you please point out the cause of the problem?
List of favorite songs:
#Environment(\.managedObjectContext) var managedObjectContext
#FetchRequest(
entity: Song.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Song.number, ascending: true)],
predicate: NSPredicate(format: "favorite <> 'false'")
) var songs: FetchedResults<Song>
var body: some View {
NavigationView{
VStack{
List {
ForEach(songs, id:\.self){ song in
NavigationLink(destination: DetailView(song: song, isSelected: song.favorite)) {
HStack{
Text("\(song.number). ") .font(.headline) + Text(song.title ?? "No title")
}
}
}
}
}
.listStyle(InsetListStyle())
.navigationTitle("Favorite")
}
}
}
Detailed view:
struct DetailView: View {
#State var song : Song
#State var isSelected: Bool
#State var wrongNumber: Bool = false
var body: some View {
VStack{
Text(song.content!)
.padding()
Spacer()
}
.navigationBarTitle("\(song.number). \(song.title ?? "No title")", displayMode: .inline)
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
HStack{
Button(action: {
song.favorite.toggle()
PersistenceController.shared.save()
isSelected=song.favorite
}) {
Image(systemName: "heart.fill")
.foregroundColor(isSelected ? .red : .blue)
}
Button(action: {
alert()
}) {
Image(systemName: "1.magnifyingglass")
}
NavigationLink("DetailView", destination: DetailView(song: song, isSelected: isSelected))
.frame(width: 0, height: 0)
.hidden()
}
}
}
}
}

Use this NSPredicate
NSPredicate(format: "favorite = %d", false)

Related

Swiftui-Picker doesn't show selected value [duplicate]

This question already has an answer here:
Choosing CoreData Entities from form picker
(1 answer)
Closed 9 months ago.
Initial position: making two pickers filled from database where the second depends on the first. I followed this Picker Values from a previous picker - CoreData/SwiftUI example and it works pretty good.
Only one problem: the second picker doesn't show the selected value.
#State var courtSelected = 0
#State var judgeSelected = 0
HStack{
Picker(selection: $courtSelected, label: Text("Gericht \(courtSelected)")){
ForEach(0..<courts.count){ court in
Text("\(courts[court].name ?? "Unknown")")
}
}
}
HStack {
Picker(selection: $judgeSelected, label: Text("Richter: (\(judgeSelected))")){
ForEach(Array(courts[courtSelected].courtsJudges! as! Set<Judges>), id: \.self) { judge in
Text("\(judge.gender ?? "") \(judge.title ?? "") \(judge.name ?? "")")
}
}
}
Only differences:
the modification from NSSet to array
I had to change #Binding var judgeSelected:Int to #State, because otherwise I have to hand over the judge selected as Parameter beginning from App-Struct.
Printing the $judgeSelected inside the label demonstrates, that this var is never changed.
Your selection and presentation are differ by type, so add tag:
Picker(selection: $courtSelected, label: Text("Gericht \(courtSelected)")){
ForEach(0..<courts.count){ court in
Text("\(courts[court].name ?? "Unknown")").tag(court) // << here !!
}
}
Second picker presents objects, so selection should also be an object, like
#State var judgeSelected: Judges? = nil
Next shows similar case so should be helpful https://stackoverflow.com/a/68815871/12299030
try something like this:
HStack{
Picker(selection: $courtSelected, label: Text("Gericht \(courtSelected)")){
ForEach(0..<courts.count){ court in
Text("\(courts[court].name ?? "Unknown")")
}
}
}
HStack {
Picker(selection: $judgeSelected, label: Text("Richter: (\(judgeSelected))")){
// -- here
ForEach(Array(Set(courts[courtSelected].courtsJudges!)), id: \.self) { judge in
Text("\(judge.gender ?? "") \(judge.title ?? "") \(judge.name ?? "")")
}
}.id(UUID()) // <-- here
}
}
Note also the second ForEach with Set. PS, do not use forced unwrap, ie. no ! in your code.
EDIT-1: to avoid the error with arrayLiteral, try this:
HStack {
Picker(selection: $judgeSelected, label: Text("Richter: (\(judgeSelected))")){
if let theJudges = courts[courtSelected].courtsJudges {
ForEach(Array(Set(theJudges)), id: \.self) { judge in
Text("\(judge.gender ?? "") \(judge.title ?? "") \(judge.name ?? "")")
}
}
}.id(UUID())
}
EDIT-2:
here is my test code that allows the second picker
to depend on the first picker. I used both the id marker, and tag that
must match the selection type.
Since you don't show your struct code for court and judge,
I created some example structs for those.
You will have to adjust the code to cater for your structs.
Used the id of the Judge struct in the second picker for the tag.
However, there are other ways to have a Int tag, for example using array indices, such as:
struct Judge: Identifiable, Hashable {
var id: Int
var gender: String?
var name: String?
var title: String?
}
struct Court: Identifiable, Hashable {
var id: Int
var name: String?
var courtsJudges: [Judge]?
}
struct ContentView: View {
#State var courtSelected = 0
#State var judgeSelected = 0
#State var courts: [Court] = [
Court(id: 0, name: "one",
courtsJudges: [
Judge(id: 0, gender: "Male", name: "name1", title: "title1"),
Judge(id: 1, gender: "Male", name: "name2", title: "title2"),
Judge(id: 2, gender: "Male", name: "name3", title: "title3")
]),
Court(id: 1, name: "two",
courtsJudges: [
Judge(id: 3, gender: "Female", name: "name7", title: "title7"),
Judge(id: 4, gender: "Female", name: "name8", title: "title8"),
Judge(id: 5, gender: "Female", name: "name9", title: "title9")
])
]
var body: some View {
VStack (spacing: 77) {
HStack{
Picker(selection: $courtSelected, label: Text("Gericht \(courtSelected)")){
ForEach(0..<courts.count) { court in
Text("\(courts[court].name ?? "Unknown")").tag(court)
}
}
}
HStack {
Picker(selection: $judgeSelected, label: Text("Richter: (\(judgeSelected))")){
if let theJudges = courts[courtSelected].courtsJudges {
ForEach(Array(Set(theJudges))) { judge in
Text("\(judge.gender ?? "") \(judge.title ?? "") \(judge.name ?? "")")
.tag(judge.id)
}
}
}.id(UUID())
}
}.padding()
}
}
Alternatively:
HStack {
Picker(selection: $judgeSelected, label: Text("Richter: (\(judgeSelected))")){
if let theJudges = courts[courtSelected].courtsJudges, let arr = Array(Set(theJudges)) {
ForEach(arr.indices, id: \.self) { index in
Text("\(arr[index].gender ?? "") \(arr[index].title ?? "") \(arr[index].name ?? "")")
.tag(index)
}
}
}.id(UUID())
}
First: thanks for all the great help so far.
Bringing it all together til now.
The following code creates a picker, but the selection is not shown. Changing to a radioGroup, you can't select anything.
Here's my edited code
struct ContentView: View {
#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Courts.name, ascending: true)],
animation: .default
)
private var courts: FetchedResults<Courts>
#State var courtSelected = 0
#State var judgeSelected = 0
var body: some View {
HStack{
Picker(selection: $courtSelected, label: Text("Gericht")){
ForEach(0..<courts.count){ court in
Text("\(courts[court].name ?? "Unknown")").tag(court)
}
}
}
HStack {
Picker(selection: $judgeSelected, label: Text("Richter \(judgeSelected)")){
ForEach(Array(courts[courtSelected].courtsJudges as! Set<Judges>), id: \.self) { judge in
Text("\(judge.gender ?? "") \(judge.title ?? "") \(judge.name ?? "")").tag(judge)
}
}.id(UUID())
}
}
}
The next code still leads to an error
HStack {
Picker(selection: $judgeSelected, label: Text("Richter: (\(judgeSelected))")){
if let theJudges = courts[courtSelected].courtsJudges {
ForEach(Array(Set(theJudges)), id: \.self) { judge in
Text("\(judge.gender ?? "") \(judge.title ?? "") \(judge.name ?? "")")
}
}
}.id(UUID())
}
I think, the problem has to be anywhere else, because already at the start the picker doesn't show anything and the radios are grey.
Is it, because picker 2 depends on picker 1 and changes when a value in picker 1 is selected?
It's all for macOS on xcode 13.4.1
I created a complete new project with core data, added two entities (Courts and Judges) with two attributes each (id and name).
Then I only made this view:
import SwiftUI
import CoreData
struct ContentView: View {
#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Courts.name, ascending: true)],
animation: .default
)
private var courts: FetchedResults<Courts>
#FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Judges.name, ascending: true)],
animation: .default
)
private var judges: FetchedResults<Judges>
#State var courtSelected = 0
#State var judgeSelected = 0
var body: some View {
if(courts.count > 0) {
HStack{
Picker(selection: $courtSelected, label: Text("Gericht")){
ForEach(0..<courts.count){ court in
Text("\(courts[court].name ?? "Unknown")").tag(court)
}
}
}
HStack {
Picker(selection: $judgeSelected, label: Text("Richter \(judgeSelected)")){
ForEach(Array(courts[courtSelected].courtsJudges as! Set<Judges>), id: \.self) { judge in
Text("\(judge.name ?? "")").tag(judge)
}
}.id(UUID())
}
HStack {
Button("neue Gerichte") {
addItem()
addJudges()
}
}
}
}
private func addItem() {
for id in 0..<3 {
let newItem = Courts(context: viewContext)
newItem.id = UUID()
newItem.name = "Gericht Nr. \(id)"
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func addJudges() {
for cd in 0..<courts.count {
for jd in 0..<3 {
let newJudge = Judges(context: viewContext)
newJudge.id = UUID()
newJudge.name = "Richter \(jd) am Gericht \(courts[cd].name)"
newJudge.judgesCourts = courts[cd]
try? viewContext.save()
}
}
}
}
The result: both pickers are shown, first ist ok, second shows the right judges, but they are not "selectable"

Core Data, Problem with updating (duplicating instead)

I am new to Swift UI. Could you please help me with core data updating?
Here is the point of a problem:
I am building a WatchOS app. There are 3 Views there:
FirstView - a view with a button to Add a new Goal and a List of added Goals.
AddGoalView - appears after pressing Add new Goal.
RingView - a view with a Goal Ring (similar to activity ring mechanics) and all the data presented.
The point of the problem is the next:
After adding a new Goal everything is alright. The Data passes correctly from AddGoalView to the FirstView. I need only 2 items to be passed out of AddGoalView (One String and one Double).
Then, after pressing on the recently created Goal I appear on the Ring View. I successfully pass there 2 items (that String and Double I mentioned).
On the RingView I want to update the 3-rd Item (double) and send it back. So it can be updated on the FirstView.
the Result:
Instead of updating this 3-d Item it just seems to create a completely new Goal on the First View below the previous Goal. Photo
My Code (FirstView):
struct FirstView: View {
#FetchRequest (
entity:NewGoal.entity(),
sortDescriptors:[NSSortDescriptor(keyPath: \NewGoal.dateAdded, ascending: false)],
animation: .easeInOut )
var results:FetchedResults<NewGoal>
#State var showMe = false
var body: some View {
ScrollView{
VStack{
VStack(alignment: .leading){
Text("My Goals:")
NavigationLink(
destination: AddGoalView(),
isActive: $showMe,
label: {
Image(systemName: "plus")
Text("Set Money Goal")
})
Text("Recents:")
ForEach(results){ item in
VStack(alignment: .leading){
NavigationLink(
destination: RingView(GTitle: item.goalTitle ?? "", Sum: item.neededSum),
label: {
HStack{
Image(systemName: "gear")
VStack(alignment: .leading){
Text(item.goalTitle ?? "")
HStack{
Text("$\(item.yourSum, specifier: "%.f")") ///This item doesn't update
Text("/ $\(item.neededSum, specifier: "%.f")")
}
}
}
})
}
}
}
}
}
}
}
My Code (AddGoalView):
struct AddGoalView: View {
#State private var goalTitle = ""
#State private var showMe:Bool = true
#State private var neededSum:Double = 0.0
#State private var isFocusedNum = false
#Environment(\.managedObjectContext) var context
#Environment(\.presentationMode) var presentationMode
var body: some View {
ScrollView{
VStack (alignment: .leading, spacing: 6){
TextField("Goal Name...", text: $goalTitle)
HStack{
Text("$\(neededSum, specifier: "%.f")")
.overlay(
RoundedRectangle(cornerRadius: 9)
.stroke(isFocusedNum ? Color.red : Color.white, lineWidth: 1)
.opacity(1.0))
.focusable(true) { newState in isFocusedNum = newState}
.animation(.easeInOut(duration: 0.1), value: isFocusedNum)
.digitalCrownRotation(
$neededSum,
from: 0,
through: 100000,
by: 25,
sensitivity: .high)
}
Button(action: addGoal) {
Text("Add Goal")
}
.disabled(neededSum == 0.0)
.disabled(goalTitle == "")
.navigationTitle("Edit")
}
}
}
private func addGoal(){
let goal = NewGoal(context: context)
goal.goalTitle = goalTitle
goal.dateAdded = Date()
goal.neededSum = neededSum
do{
try context.save()
presentationMode.wrappedValue.dismiss()
}catch let err{
print(err.localizedDescription)
}
}
My Code (RingView Code):
struct RingView: View {
#State private var isFocusedSum = false
#State private var yournewSum:Double = 0.0
var goalItem: NewGoal?
var Sum:Double
var GTitle:String
#Environment(\.managedObjectContext) var context
#Environment(\.presentationMode) var presentationMode
#FetchRequest var results: FetchedResults<NewGoal>
init(GTitle: String, Sum: Double){
self.GTitle = GTitle
self.Sum = Sum
let predicate = NSPredicate(format:"goalTitle == %#", GTitle)
self._results=FetchRequest(
entity: NewGoal.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \NewGoal.dateAdded, ascending: false)],
predicate: predicate,
animation: .easeInOut
)
}
var body: some View {
ZStack{
ForEach(results) { item in
RingShape(percent:(yournewSum/item.neededSum*100), startAngle: -90, drawnClockwise: false) /// Ring
.stroke(style: StrokeStyle(lineWidth: 10, lineCap: .round))
.fill(AngularGradient(gradient: Gradient(colors: [.red, .pink, .red]), center: .center))
.frame(width: 155, height: 155)
HStack(alignment: .top){
Spacer()
Button(action: addSum) { ///BUTTON TO Update
Image(systemName: "gear")
}
.clipShape(Circle())
}
VStack(alignment: .trailing, spacing: 0.0){
Spacer()
Text("$\(yournewSum, specifier: "%.f")") /// Here is the data I want to change via Digital Crown and update
.font(.title3)
.overlay(
RoundedRectangle(cornerRadius: 7)
.stroke(Color.white, lineWidth: 2)
.opacity(isFocusedSum ? 1.0:0.0)
)
.focusable(true) { newState in isFocusedSum = newState}
.animation(.easeInOut(duration: 0.3), value: isFocusedSum)
.digitalCrownRotation(
$yournewSum,
from: 0,
through: Double((item.neededSum)),
by: 10,
sensitivity: .high)
Text("/ $\(item.neededSum, specifier: "%.f")") ///Here is the Double data I entered in AddGoalView
.font(.caption)
}
.frame(width: 200, height: 230)
.padding(.top, 7)
VStack(alignment: .center, spacing: 1.0){
Text(item.goalTitle ?? "Your Goal Name") ///Here is the String data I entered in AddGoalView
.foregroundColor(.gray)
}
.padding(.top, 200.0)
}
}
.padding([.top, .leading, .trailing], 5.0)
}
private func addSum(){
let goal = goalItem == nil ? NewGoal(context: context): goalItem
goal?.yourSum = yournewSum //// I am trying to update the Data here, but after running the func it creates a duplicate.
do{
try context.save()
presentationMode.wrappedValue.dismiss()
} catch let err{
print(err.localizedDescription)
}
}
You never give var goalItem: NewGoal? the initial value of the item you want to update.
try replacing this
RingView(GTitle: item.goalTitle ?? "", Sum: item.neededSum)
with
RingView(goalItem: item, GTitle: item.goalTitle ?? "", Sum: item.neededSum)
and of course your have to change your initializer for RingView to
init(goalItem: NewGoal? = nil, GTitle: String, Sum: Double){
and add to the initializer this line
self.goalItem = goalItem

Updating core data entity with observedobject

I have created a list of clients which get saved in core data. I added some attributes through an AddView and now I am trying to add a new attribute using a different view. In order to do that I understood I need to use the observedObject property wrapper so that it doesn't create a new client but update the existing one. This is the code:
import SwiftUI
import CoreData
struct TopicView: View {
#Environment(\.managedObjectContext) var managedObjectContext
#Environment (\.presentationMode) var presentationMode
#ObservedObject var topic: StudentData
#State var content = ""
#State private var show = false
#StateObject private var keyboard = Keyboard()
var body: some View {
Form{
Section (header: Text("Topics covered")
.bold()
.padding(.all)
.font(.title3)) {
TextEditor(text: Binding(
get: {self.topic.content ?? ""},
set: {self.topic.content = $0 } ))
.frame(height: 250)
}
}.onTapGesture {
hideKeyboard()
}
}
}
Button ("Submit")
{
self.topic.content = self.content
self.topic.objectWillChange.send()
try? self.managedObjectContext.save()
self.presentationMode.wrappedValue.dismiss()
}.foregroundColor(.white)
This is the view where the new attribute should be shown:
import SwiftUI
import CoreData
import MapKit
struct StudentView: View {
#Environment(\.managedObjectContext) var managedObjectContext
#FetchRequest(entity: StudentData.entity(),
sortDescriptors: [],
animation: .spring()) var content: FetchedResults<StudentData>
#Environment (\.presentationMode) var presentationMode
#ObservedObject var topic: StudentData
#State var showModalView = false
#State private var showingSheet = false
let myStudent: StudentData
var body: some View {
NavigationView {
VStack{
Text("Topics Covered")
.font(.system(size: 30, weight: .bold, design: .rounded))
.foregroundColor(.red)
.padding(.horizontal)
Text("\(myStudent.content ?? "")")
.font(.title2)
.bold()
.foregroundColor(.white)
.padding(.horizontal) }}
Spacer()
Spacer()
}.sheet(isPresented: $showModalView, content: {
TopicView(topic: topic)})
The problem is, if I type in the texteditor some text without save it then it shows correctly in the other view. However, when I save it, it does not show in the other view.
Is there anything wrong in my save code?

SwiftUI layout grows outside the bounds of the device when using .edgesIgnoringSafeArea()

Having an issue in SwiftUI where some Views are growing bigger vertically than the size of the device when using .edgesIgnoringSafeArea(.bottom). On an iPhone 11 Pro which is 812 pixels high I am seeing a view of size 846. I am using the Debug View Hierarchy to verify it. This has been tested on Xcode 11.4.1 and 11.1 and exists in both versions and probably all in between.
I have included sample code below.
I am pretty sure this is a SwiftUI bug, but was wondering if anyone has a workaround for it. I need the edgesIgnoringSafeArea(.bottom) code to draw the TabBar, and for the ProfileView() to extend to the bottom of the screen when I hide my custom tab bar.
struct ContentView: View {
var body: some View {
MainTabView()
}
}
struct MainTabView : View {
enum Item : CaseIterable {
case home
case resources
case profile
}
#State private var selected : Item = .home
var body: some View {
VStack(spacing: 0.0) {
ZStack {
HomeView()
.zIndex(selected == .home ? 1 : 0)
ResourcesView()
.zIndex(selected == .resources ? 1 : 0)
ProfileView()
.zIndex(selected == .profile ? 1 : 0)
}
// Code here for building and showing/hiding a Toolbar
// Basically just a HStack with a few buttons in it
}
.edgesIgnoringSafeArea(.bottom) // <- This causes the screen to jump to 846
}
}
struct ProfileView : View {
#State private var showQuestionnaireView = false
var body: some View {
NavigationView {
ZStack {
NavigationLink(destination: QuestionnaireView( showQuestionnaireView:$showQuestionnaireView),
isActive: $showQuestionnaireView) {
Text("Show Questionnaire View")
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
}
struct QuestionnaireView : View {
#Binding var showQuestionnaireView : Bool
var body: some View {
GeometryReader { screenGeometry in
ZStack {
Color.orange
VStack {
Text("Top")
Spacer()
Text("Bottom")
}
}
}
}
}
HomeView() and ResourcesView() are just copies of ProfileView() that do their own thing.
When you run it you will see a button, push the button and a hidden Navigation Stack View pushes on the QuestionnaireView, this view contains a VStack with two text fields, neither of which you will be able to see due to this issue. Understandably the top one is behind the notch, but the bottom one is off the bottom of the screen. In my real project this issue is rarely seen at runtime, but switching between dark mode and light mode shows it. In the above code there is no need to switch appearances.
EDIT: FB7677794 for anyone interested, have not received any updates from Apple since lodging it 3 weeks ago.
EDIT2: Added some more code to MainTabBar
Update: This is fixed in Xcode 12 Beta 2
After reading the updated question I have made some changes and tried to make a small demo. In this, I am using the same approach as before, put NavigationView in your main tab view and with this you don't have to hide and show every time you come or leave your main tab view.
import SwiftUI
struct ContentView: View {
var body: some View {
MainTabView()
}
}
struct MainTabView : View {
enum Item : CaseIterable {
case home
case resources
case profile
}
#State private var selected : Item = .home
var body: some View {
NavigationView {
VStack(spacing: 0.0) {
ZStack {
Group {
HomeView()
.zIndex(selected == .home ? 1 : 0)
ResourcesView()
.zIndex(selected == .resources ? 1 : 0)
ProfileView()
.zIndex(selected == .profile ? 1 : 0)
}
.frame(minWidth: .zero, maxWidth: .infinity, minHeight: .zero, maxHeight: .infinity)
.background(Color.white)
}
HStack {
Group {
Image(systemName: "house.fill")
.onTapGesture {
self.selected = .home
}
Spacer()
Image(systemName: "plus.app.fill")
.onTapGesture {
self.selected = .resources
}
Spacer()
Image(systemName: "questionmark.square.fill")
.onTapGesture {
self.selected = .profile
}
}
.padding(.horizontal, 30)
}
.frame(height: 40)
.foregroundColor(Color.white)
.background(Color.gray)
// Code here for building and showing/hiding a Toolbar
// Basically just a HStack with a few buttons in it
}
.edgesIgnoringSafeArea(.bottom)
} // <- This causes the screen to jump to 846
}
}
struct ProfileView : View {
#State private var showQuestionnaireView = false
var body: some View {
// NavigationView {
ZStack {
NavigationLink(destination: QuestionnaireView( showQuestionnaireView:$showQuestionnaireView),
isActive: $showQuestionnaireView) {
Text("Show Questionnaire View")
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
// }
}
}
struct QuestionnaireView : View {
#Binding var showQuestionnaireView : Bool
var body: some View {
GeometryReader { screenGeometry in
ZStack {
Color.orange
VStack {
Text("Top")
Spacer()
Text("Bottom")
}
}
.edgesIgnoringSafeArea(.bottom)
}
}
}
struct HomeView: View {
var body: some View {
NavigationLink(destination: SecondView()) {
Text("Home View")
}
}
}
struct ResourcesView: View {
var body: some View {
NavigationLink(destination: SecondView()) {
Text("Resources View")
}
}
}
struct SecondView: View {
var body: some View {
Text("Second view in navigation")
.background(Color.black)
.foregroundColor(.white)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewDevice(PreviewDevice(rawValue: "iPhone 11"))
}
}
It is due to undefined size for NavigationView. When you add your custom tab bar component, as in example below, that limits bottom area, the NavigationView will layout correctly.
Tested with Xcode 11.4 / iOS 13.4
struct MainTabView : View {
var body: some View {
VStack(spacing: 0.0) {
ZStack {
Color(.cyan)
ProfileView() // << this injects NavigationView
}
HStack { // custom tab bar
Button(action: {}) { Image(systemName: "1.circle").padding() }
Button(action: {}) { Image(systemName: "2.circle").padding() }
Button(action: {}) { Image(systemName: "3.circle").padding() }
}.padding(.bottom)
}
.edgesIgnoringSafeArea(.bottom) // works !!
}
}

How to deal with master/detail CoreData between SwiftUI views

I'm dealing with issue how to pass parameter selected in master view to CoreData predicate in detail view. I have this master view
struct ContentView: View {
#State private var selectedCountry: Country?
#State private var showSetting = false
#FetchRequest(entity: Country.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Country.cntryName, ascending: true)]
) var countries: FetchedResults<Country>
var body: some View {
NavigationView {
VStack {
Form {
Picker("Pick a country", selection: $selectedCountry) {
ForEach(countries, id: \.self) { country in
Text(country.cntryName ?? "Error").tag(country as Country?)
}
}
if selectedCountry != nil {
Years(cntryName: selectedCountry?.cntryName! ?? "")
}
}
}
.navigationBarTitle("UNECE Data")
.navigationBarItems(trailing: Button("Settings", action: {
self.showSetting.toggle()
}))
}
.sheet(isPresented: $showSetting) {
SettingsView(showSetting: self.$showSetting)
}
}
}
where I use Picker to select country name (from CoreData entity Country and its attribute cntryName) and pass it as String value to Years view which is coded like this
struct Years: View {
var cntryName: String
#State private var selectedDataRow: Data?
#State private var result: NSFetchRequestResult
#FetchRequest(entity: Data.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Data.dataYear, ascending: true)],
predicate: NSPredicate(format: "dataCountry == %#", "UK"), animation: .default
) var data: FetchedResults<Data>
var body: some View {
Picker("Year", selection: $selectedDataRow) {
ForEach(data, id: \.self) { dataRow in
Text(dataRow.dataYear ?? "N/A")
}
}
.pickerStyle(WheelPickerStyle())
.frame(width: CGFloat(UIScreen.main.bounds.width), height: CGFloat(100))
.clipped()
.onAppear() {
let request = NSFetchRequest<Data>(entityName: "Data")
request.sortDescriptors = [NSSortDescriptor(key: "dataYear", ascending: true)]
request.predicate = NSPredicate(format: "dataCountry == %#", self.cntryName)
do {
self.result = try context.fetch(request) as! NSFetchRequestResult
print(self.result)
} catch let error {
print(error)
}
}
}
}
It works fine with #FetchRequest and FetchedResults stored in var data but I'm wondering how to build predicate here based on passed country name. To overcome this I considered to use onAppear section and classic NSFetchRequest and NSFetchRequestResult which causes compiler error "'Years.Type' is not convertible to '(String, NSFetchRequestResult, FetchRequest) -> Years'" in the line
Years(cntryName: selectedCountry?.cntryName! ?? "")
of ContentView struct. Error disappear if I comment the line
#State private var result: NSFetchRequestResult
in Years struct but it obviously causes another error. So I'm lost in circle. What`s recommended practice here, please?
Thanks.
Finally I found the way thanks to this post SwiftUI use relationship predicate with struct parameter in FetchRequest
struct Years: View {
var request: FetchRequest<Data>
var result: FetchedResults<Data> {
request.wrappedValue
}
#State private var selectedDataRow: Data?
init(cntryName: String) {
self.request = FetchRequest(entity: Data.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Data.dataYear, ascending: true)],
predicate: NSPredicate(format: "dataCountry == %#", cntryName), animation: .default)
}
var body: some View {
VStack {
Picker("Year", selection: $selectedDataRow) {
ForEach(result, id: \.self) { dataRow in
Text(dataRow.dataYear ?? "N/A").tag(dataRow as Data?)
}
}
.pickerStyle(WheelPickerStyle())
.frame(width: CGFloat(UIScreen.main.bounds.width), height: CGFloat(100))
.clipped()
VStack(alignment: .leading, spacing: 10) {
HStack {
Text("Total polutation: ")
.alignmentGuide(.leading) { dimension in
10
}
if selectedDataRow != nil {
Text(String(describing: selectedDataRow!.dataTotalPopulation))
} else {
Text("N/A")
}
}
}}
}
}

Resources