Need help passing CoreData to another view after its saved to the database. I have a separate view to "Add Items" and the List View shows the items, sorted. With NavigationView I can tap to see each entry, but I want to .onTapGesture overlay a new View with the list items that are editable.
Struggling to figure this out.
Right now this works to see more detail of each list item, but I'd rather have it open a new view with an .onTapGesture but can't figure out how to pass the database item tapped to the new View and set it to edit.
NavigationView{
List {
ForEach(newItem) { newItems in
NavigationLink(destination: TapItemView(database: newItems)) {
DatabaseRowView(database: newItems)}
}
}.onDelete(perform: deleteItem)
}
?
An observation: in your code sample--"ForEach(newItem) { newItems in" should be "ForEach(newItems) { newItem in". In other words the collection goes in the ForEach parentheses and the single item precedes the "in". With that, I started with the Xcode-generated project with Core Data for this example (Xcode Version 13.1). Modifications are included in the code below.
#State var showEditView = false
#State var tappedItem: Item = Item()
var body: some View {
NavigationView {
List {
ForEach(items) { item in
Text(item.timestamp, formatter: itemFormatter)
.onTapGesture {
tappedItem = item
showEditView = true
}
}
.sheet(isPresented: $showEditView) {
EditView(item: $tappedItem)
}
}
}
}
Here's a possible receiving view for the tapped item:
struct EditView: View {
#Binding var item: Item
var body: some View {
NavigationView {
Form {
Section(header: Text("Date")) {
DatePicker("Date Selection",
selection: $item.timestamp,
displayedComponents: [.date]
)
.datePickerStyle(.compact)
.labelsHidden()
}
}
}
}
Related
I am using coredata to save information. This information populates a picker, but at the moment there is no information so the picker is empty. The array is set using FetchedRequest.
#FetchRequest(sortDescriptors: [])
var sources: FetchedResults<Source>
#State private var selectedSource = 0
This is how the picker is setup.
Picker(selection: $selectedSource, label: Text("Source")) {
ForEach(0 ..< sources.count) {
Text(sources[$0].name!)
}
}
There is also a button that displays another sheet and allows the user to add a source.
Button(action: { addSource.toggle() }, label: {
Text("Add Source")
})
.sheet(isPresented: $addSource, content: {
AddSource(showSheet: $addSource)
})
If the user presses Add Source, the sheet is displayed with a textfield and a button to add the source. There is also a button to dismiss the sheet.
struct AddSource: View {
#Environment(\.managedObjectContext) var viewContext
#Binding var showSheet: Bool
#State var name = ""
var body: some View {
NavigationView {
Form {
Section(header: Text("Source")) {
TextField("Source Name", text: $name)
Button("Add Source") {
let source = Source(context: viewContext)
source.name = name
do {
try viewContext.save()
name = ""
} catch {
let error = error as NSError
fatalError("Unable to save context: \(error)")
}
}
}
}
.navigationBarTitle("Add Source")
.navigationBarItems(trailing: Button(action:{
self.showSheet = false
}) {
Text("Done").bold()
.accessibilityLabel("Add your source.")
})
}
}
}
Once the sheet is dismissed, it goes back to the first view. The picker in the first view is not updated with the newly added source. You have to close it and reopen. How can I update the picker once the source is added by the user? Thanks!
The issue is with the ForEach signature you're using. It works only for constant data. If you want to use with changing data, you have to use something like:
ForEach(sources, id: \Source.name.hashValue) {
Text(verbatim: $0.name!)
}
Note that hashValue will not be unique for two entity objects with the same name. This is just an example
I want to basically make didSelectRow like UITableView in SwiftUI.
This is the code:
struct ContentView: View {
var testData = [Foo(name: "1"),
Foo(name: "2"),
Foo(name: "3"),
Foo(name: "4"),
Foo(name: "5")]
#State var selected: Foo?
var body: some View {
NavigationView {
VStack {
List(testData, id: \.name, selection: $selected) { foo in
HStack {
Text(foo.name)
}
}.navigationBarTitle("Selected \(selected?.name ?? "")")
Button("Check:") {
print(selected?.name)
}
}
}
}
I was thought if I click the cell then selected should contains the selected value, but it's not. The selected has no value. And the cell not clickable.
So I added a Button.
NavigationView {
VStack {
List(testData, id: \.name, selection: $selected) { foo in
HStack {
Text(foo.name)
Button("Test") {
print("\(foo) is selected.")
print(selected?.name)
}
}
}.navigationBarTitle("Selected \(selected?.name ?? "")")
Button("Check:") {
print(selected?.name)
}
}
Now, click works, but actually foo is the one I want there's no need selected why selection of the List is here.
Not sure anything I missed. Should the Button is necessary for the List "didSelectRow"? thanks!
EDIT
After a bit more investigation, my current conclusion is:
For single selections, no need call List(.. selection:). But you have to use Button or OnTapGesture for clickable.
List(.. selection:) is only for edit mode, which is multiple selection, as you can see the selection: needs a set. My example should be
#State var selected: Set<Foo>?
On iOS selection works in Edit mode by design
/// Creates a list with the given content that supports selecting multiple
/// rows.
///
>> /// On iOS and tvOS, you must explicitly put the list into edit mode for
>> /// the selection to apply.
///
/// - Parameters:
/// - selection: A binding to a set that identifies selected rows.
/// - content: The content of the list.
#available(watchOS, unavailable)
public init(selection: Binding<Set<SelectionValue>>?, #ViewBuilder content: () -> Content)
so you need either add EditButton somewhere, or activate edit mode programmatically, like
List(selection: $selection) {
// ... other code
}
.environment(\.editMode, .constant(.active)) // eg. persistent edit mode
Update: Here is some demo of default SwiftUI List selection
struct DemoView: View {
#State private var selection: Set<Int>?
#State private var numbers = [0,1,2,3,4,5,6,7,8,9]
var body: some View {
List(selection: $selection) {
ForEach(numbers, id: \.self) { number in
VStack {
Text("\(number)")
}
}.onDelete(perform: {_ in})
}
.environment(\.editMode, .constant(.active))
}
}
The use case is pretty simple. I have a List of places, and each corresponds to a geofence. I need to enable navigation in that particular row(s) whose geofence the user is inside. And the list is dynamic and is fetched from an API. There are similar question on Stackoverflow, but those address only static lists.
I tried using a dictionary of bools, but I am not able to make it work.
This is a simplified mock code:
struct ListView: View {
#State private var navActive: [UUID: Bool] = [:]
var body: some View {
List (viewModel.allItems, id: \.id) { item in
NavigationLink(destination: DetailView(item), isActive: $navActive[item.id]) {
Text(item.name)
.onTapGesture {
if currentLocation.isInside(item.geofence) { navActive[item.id] = true }
}
}
}
}
}
I get this error: Cannot convert value of type 'Binding<Bool?>' to expected argument type 'Binding<Bool>'
on the NavigationLink isActive argument.
Note: I've populated the navActive dictionary with key-value pairs on receiving allItems with an onRecieve modifier
Here is a possible approach for your use-case
struct ListView: View {
// ... your view model defined here
#State private var selectedItem: UUID? = nil
var body: some View {
List (viewModel.allItems, id: \.id) { item in
Text(item.name)
.onTapGesture {
self.selectedItem = item.id
}
.background(
NavigationLink(destination: DetailView(item), tag: item.id,
selection: $selectedItem) { EmptyView() }
.buttonStyle(PlainButtonStyle())
)
}
}
}
I have a very simple schoolbook example of a SwiftUI List view that renders items from data in an array. Data in the array is Identifiable. But, when I change the the data in the array, add or remove a item then all rows in the list view are recreated. Is that correct? My understanding was that Identifiable should make sure that only the view in the list that are changed are recreated.
My list is inside a navigation view and each row links to a detail view. The problem is that since all items in the list are removed and recreated every time the data is changed then if that that happens when Im in a detail view (it's triggered by a notification) then Im thrown out back to the list.
What am I missing?
Edit: Added code example
This is my data struct:
struct Item: Identifiable {
let id: UUID
let name: String
init(name: String) {
self.id = UUID()
self.name = name
}
}
This is my ItemView
struct ItemView: View {
var item: Item
init(item: Item) {
self.item = item
print("ItemView created \(self.item.id)")
}
var body: some View {
Text(self.item.name)
}
}
An finally my list view:
struct KeyList: View {
#State var items = [Item(name: "123"), Item(name: "456"), Item(name: "789")]
var body: some View {
VStack {
List(self.items) { item in
ItemView(item: item)
}
Button(action: {
self.items.append(Item(name: "New"))
}) {
Text("Add")
}
}
}
}
When I press add it will print "ItemView created" 4 times. My understanding is that it should only do it 1 time?
Here is an example of how this could work. Tested and working on iOS 13.5
The List doesn't get recreated again when only one item is being removed. So this was accomplished.
About the poping of the View this has already been answered here:
SwiftUI ForEach refresh makes view pop
I have here a small workaround for this problem. Add the items you want to remove to an array. Then when going back, remove these items (Which will make the view pop) or go back programmatically and nothing gets removed
struct ContentView: View {
#State var text:Array<String> = ["a", "b", "c"]
var body: some View {
NavigationView() {
VStack() {
List() {
ForEach(self.text, id: \.self){ item in
NavigationLink(destination: SecondView(textItem: item, text: self.$text)) {
Text(item)
}
}
}
Button(action: {
self.text.remove(at: 0)
}){
Text("Remove \(self.text[0])")
}
}
}
}
}
struct SecondView: View {
#State var textItem: String
#Binding var text: Array<String>
#State var tmpArray: Array<String> = []
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack() {
Text(self.textItem)
Button(action: {
//Append to a tmp array which will later be used to determine what to remove
self.tmpArray.append(self.text[0])
}){
Text("Remove \(self.text[0])")
}
Button(action: {
if self.tmpArray.count > 0 {
//remove your stuff which will automatically pop the view
self.text.remove(at: 0)
} else {
// programmatically go back as nothing has been deleted
self.presentationMode.wrappedValue.dismiss()
}
}){
Text("Go Back")
}
}
}
}
Using Xcode 11.0, Beta 5.
I have a List driven from an array of model objects in an observed view model. Each item in the List has a NavigationLink with a destination detail view/view model that accepts the model as an argument.
The user can tap a bar button above the list to add a new item which is added to the view model's array and the List is therefore reloaded with the new item displayed.
The issue I cannot solve is how to select that new item in the list and therefore display the detail view without needing the user to select it manually. (This is an iPad app with split screen view, hence the reason to want to select it)
I've tried using a NavigationLink programatically, but can't seem to get anything to work. I looked at the selection argument for the List but that also requires the list to be in edit mode, so that's no good.
Any suggestions are very welcome!
The following solution uses the selection attribute of NavigationLink. One problem here is that only items currently visible get rendered, so selecting a row further down does nothing.
import SwiftUI
struct Item: Identifiable {
let id = UUID()
var title: String
var content: String
}
struct ItemOverview: View {
let item: Item
var body: some View {
Text(item.title)
}
}
struct ItemDetailsView: View {
let item: Item
var body: some View {
VStack{
Text(item.title).font(.headline)
Divider()
Text(item.content)
Spacer()
}
}
}
func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
}
struct ListSelectionView: View {
#State var items: [Item] = [
Item(title: "Hello", content: "Content World"),
Item(title: "Hey", content: "Content Du"),
]
#State var selection: UUID? = nil
func createItem() {
let newItem = Item(title: randomString(length: 3), content: randomString(length: 10))
self.selection = newItem.id
self.items.append(newItem)
}
var body: some View {
VStack{
NavigationView{
List(items) { item in
NavigationLink(destination: ItemDetailsView(item: item), tag: item.id, selection: self.$selection, label: {
Text(item.title)
})
}
}
Button(action: {
self.createItem()
}) { Text("Add and select new item") }
Divider()
Text("Current selection2: \(String(selection?.uuidString ?? "not set"))")
}
}
}
A second problem is that changing the $selection makes Modifying state during view update appear.
Third problem is that after manual selection the shading stays on the same item until again changed by hand.
Result
Programmatic selection is not really usable for now if you want to select a link not initialized yet (not visible?).
Further ideas
One might look into tags a little bit more.
Another option could be paging where all items of the current page are visible.
One could also use list selection and show details based on that.