How to make navigation link to expandable list in SwiftUI - xcode

I am trying to make navigation links to an expandable list.
I want to make navigation links only to sub-lists like "UICollectionView", "UIScrollView", "NavigationView", and "Expanding Rows".
But I don't know how to deal with this problem.
If someone helped me, I would appreciate it.
import SwiftUI
struct TutorialItem: Identifiable {
let id = UUID()
let title: String
var tutorialItems: [TutorialItem]?
}
struct ContentView: View {
var body: some View {
let tutorialItems: [TutorialItem] = [sampleUIKit(), sampleSwiftUI()]
List(tutorialItems, children: \.tutorialItems){
tutorial in
Text(tutorial.title)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
func sampleUIKit() -> TutorialItem {
return .init(title: "UIKit", tutorialItems:
[.init(title: "UICollectionView"),
.init(title: "UIScrollView")])
}
func sampleSwiftUI() -> TutorialItem {
return .init(title: "SwiftUI", tutorialItems:
[.init(title: "NavigationView"),
.init(title: "Expanding Rows")])
}
'''

I tried and below worked for me
#State var favItems = [BookmarkItem]()
var body: some View {
if #available(iOS 14.0, *) {
List {
ForEach(favItems) { item in
Section(header: Text(item.title)) {
OutlineGroup(
item.bookmarkItems ?? [],
id: \.id,
children: \.bookmarkItems
) { tree in
NavigationLink(destination: Text("-- \(tree.desc)")) {
Text("\(tree.desc)")
.font(.subheadline)
}
}
}
}
}.listStyle(SidebarListStyle())
} else {
// Fallback on earlier versions
}
}
//BookmarkItems
struct BookmarkItem: Identifiable {
var id = UUID()
var title: String
var desc: String
var bookmarkItems: [BookmarkItem]?
}

Related

Passing data with NavigationSplitView to the second column

I have a macOS app with two columns. The left column is a list that presents the filename and date of the unit (file) that I'm working on. The second column, to the right, should present the content of each file when selected.
I have an array that contains that information and I create a list for the left column that presents each item. I added a detail: with a TextEditor that allows the user to see the data and modify it if necessary. I have been trying to set the #State var text to the contents of currentunit.text but I don't know how to pass that the detail:. If I try to assign it (as in text = x) then I get an error saying that it doesn't conform to View.
I tried then to maybe load it by getting the index of the current selected unit, using the selectedUnitId, and using something like this to get the index:
func getIndex(uuid: UUID) -> Int? {
return data.units.firstIndex(where: {$0.id == uuid})
}
But I get nowhere with a collection of different errors.
Regardless, how do I pass data to the detail: part of the code? I have looked into many examples of NavigationSplitView and they are all very similar, just showing the basic usage and that's it.
Thanks!
Code:
struct Unit: Codable, Hashable, Identifiable {
let id: UUID
var text: String
var date = Date()
var dateText: String {
let df = DateFormatter()
df.dateFormat = "EEEE, MMM d yyyy, h:mm a"
return df.string(from: date)
}
var changed: Bool = false
}
final class UnitModel: ObservableObject {
#AppStorage("unit") public var units: [Unit] = []
init() {
self.units = self.units.sorted(by: {
$0.date.compare($1.date) == .orderedDescending
})
}
func sortList() {
self.units = self.units.sorted(by: {
$0.date.compare($1.date) == .orderedDescending
})
}
}
struct ContentView: View {
#EnvironmentObject private var data: UnitModel
#State var selectedUnitId: UUID?
#State var text: String = ""
var body: some View {
NavigationSplitView {
List(data.units, selection: $selectedUnitId) { currentunit in
VStack(alignment: .leading) {
Text(currentunit.filename)
Text(currentunit.dateText)
}
}
} detail: {
// here: how do I preload $text with the text from the unit?
VStack(alignment: .leading) {
TextEditor(text: $text)
}
}
}
}
I also tried:
struct ContentView: View {
#EnvironmentObject private var data: UnitModel
#State var selectedNoteId: UUID?
var body: some View {
NavigationSplitView {
List(data.units, selection: $selectedNoteId) { currentunit in
NavigationLink{
UnitView(unit: currentunit, text: currentunit.text)
} label: {
VStack(alignment: .leading) {
Text(currentunit.filename)
Text(currentunit.dateText)
}
}
}
} detail: {
Text("Select a unit.")
}
}
}
struct UnitView: View {
#EnvironmentObject private var data: UnitModel
var unit: Unit
#State var text: String
var body: some View {
VStack(alignment: .leading) {
TextEditor(text: $text)
}
}
}
But again, I don't know how to initialize the text variable with the text of the current unit. I only get the initial one selected, and even tho I can see a new unit selected, the text remains the same and doesn't update.
UPDATED if I change the code to use NavigationView then it works as it should, so what's going with the new way that Apple is make us use now? Namely NavigationSplitView and NavigationStack?
Here's the code that work as it should but it's deprecated according to Apple:
NavigationView {
List(data.units, selection: $selectedNoteId) { currentunit in
NavigationLink(
destination: UnitView(unit: currentunit, text: currentunit.text),
label: {
VStack(alignment: .leading) {
Text(currentunit.filename)
Text(currentunit.dateText)
}
}
)
}
Apple's Defining the source of truth using a custom binding
tutorial covers this. Your code would look something like this:
} detail: {
DetailView(unitID: selectedUnitID) // not sure why they used binding
}
struct DetailView: View {
let unitID: Unit.ID
#EnvironmentObject private var store: UnitModel
private var unitBinding: Binding<Unit> {
Binding {
if let id = unitID {
return store.unit(with: id) ?? Unit.emptyUnit()
} else {
return Unit.emptyUnit()
}
} set: { updatedUnit in
store.update(updatedUnit)
}
}
var body: some View {
if store.contains(unitID) {
VStack(alignment: .leading) {
TextEditor(text: unitBinding.text)
}
}
else {
Text("Select Unit")
}
}
}
Note there currently (as of Xcode 14.2) is a known bug with the text cursor when using a TextField in the detail pane. Check by entering text, move cursor to middle and try to enter a character. The bug is the cursor jumps to the end.

Sending an NSManagedObjectID to a struct / view

I'm complete new to swift, swiftui and coredata. I have good programming experience in other languages, but swift is its own world. :-)
Important information: it's for macOS not iOS!!
My problem: I want to edit a Dataset in an separate view displayed in a sheet. I followed this example (SwiftUI update view on core data object change), but when trying to run, my NSManagedObjectID is allway nil.
The ContentView (shortened)
import SwiftUI
import CoreData
struct ContentView: View {
#State public var selectedBookId: NSManagedObjectID?
#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Books.title, ascending: true)],
animation: .default)
private var books: FetchedResults<Books>
#State private var showingEditScreen = false
var body: some View {
NavigationView {
List {
ForEach(books, id: \.self) { book in
HStack {
NavigationLink {
HStack {
Button {
// here store objectID to var
selectedBookId = book.objectID
showingEditScreen.toggle()
} label: {
Label("", systemImage: "pencil")
}
}
.padding(10.0)
} label: {
Text(book.title!)
}
}
}.onDelete(perform: deleteBooks)
}
.toolbar {
ToolbarItem(placement: .automatic) {
// here goes blabla
}
}
Text("Bitte zuerst ein Buch auswählen!")
}
.sheet(isPresented: $showingEditScreen) {
// Run EditBookView an send bookId
EditBookView(bookId: selectedBookId).environment(\.managedObjectContext, self.viewContext)
}
}
}
My EditView looks like this
import SwiftUI
struct EditBookView: View {
#Environment(\.managedObjectContext) var moc
#Environment(\.dismiss) var dismiss
var bookId: NSManagedObjectID! // This is allways nil!!
var book: Books {
moc.object(with: bookId) as! Books
}
#State private var title = ""
#State private var review = ""
var body: some View {
Form {
Text("Edit Book").font(.title)
Spacer()
Section {
TextField("Buchname", text: $title)
TextEditor(text: $review)
} header: {
Text("Schreibe eine Zusammenfassung")
}
Spacer()
Section {
HStack {
Button("Save") {
// add the book
// here code for update
try? moc.save()
dismiss()
}
Button("Cancel") {
print(bookId) // shows "nil"
dismiss()
}
}
}
Spacer()
}
.onAppear {
self.title = self.book.title ?? ""
self.review = self.book.review ?? ""
}
.padding(10.0)
}
}
First: thanks for all the good hints. In the end, I could solve the problem using
#ObservedObject var aBook: Books
at the beginning of my EditView.
The button itself has the following code
Button {
showingEditScreen.toggle()
} label: {
Label("", systemImage: "pencil")
}.sheet(isPresented: $showingEditScreen) {
EditBookView(aBook: book).environment(\.managedObjectContext, self.viewContext)
}
This way, I can send the whole book object of a single book item to the edit view and I can use it.

SWIFT UI add element to array

I trying to learn the new SwiftUI coding technique. I would like to click a button that will add elements to an array that is a #State variable. The button is the buttonclick function. The array is the push_group_row / push_group_array. I get an error in the append statement.
Eventually the buttonclick will access a database to build an array with more row, but for now I just trying to add one row.
Code:
import SwiftUI
import Combine
var gordon: String = "xxxxxx"
struct Result: Codable {
let trackId: Int
let trackName: String
let collectionName: String
}
struct Response: Codable {
var results: [Result]
}
struct Pokemon: Identifiable {
let id: Int
let name: String
let type: String
let color: Color
}
struct push_group_row {
let id: Int
let code: String
let title: String
}
struct ContentView: View
{
#State private var results = [Result]()
#State var pokemonList = [
Pokemon(id: 0, name: "Charmander", type: "Fire", color: .red),
Pokemon(id: 1, name: "Squirtle", type: "Water", color: .blue),
Pokemon(id: 2, name: "Bulbasaur", type: "Grass", color: .green),
Pokemon(id: 3, name: "Pikachu", type: "Electric", color: .yellow),]
#State var push_group_array = [push_group_row(id: 0, code: "code12", title: "POAFire")]
var body: some View
{
NavigationView
{
VStack(alignment: . leading){
Button(action: {
// What to perform
self.buttonclick()
}) {
// How the button looks like
Text("clickme")
.background(Color.purple)
.foregroundColor(.white)
}
List(results, id: \.trackId)
{item in
NavigationLink(destination: DetailView(lm: String(item.trackId)))
{
VStack(alignment: .leading)
{
Text(String(item.trackId))
Text(item.trackName)
.font(.headline)
Text(item.collectionName)
Text(gordon)
}
}
}
List(self.pokemonList)
{ pokemon in
HStack
{
Text(pokemon.name)
Text(pokemon.type).foregroundColor(pokemon.color)
}
}
List(push_group_array, id: \.id)
{ pg_item in
HStack
{
Text(String(pg_item.id))
Text(pg_item.code)
}
}
.onAppear(perform: self.loaddata)
}
.navigationBarTitle("x")
.navigationBarItems(
trailing: Button(action: addPokemon, label: { Text("Add") }))
Spacer()
}
}
func addPokemon() {
if let randomPokemon = pokemonList.randomElement() {
pokemonList.append(randomPokemon)
}
}
// *************************** below is the add arrat code
func buttonclick() {
let newCode = "First"
let newTitle = "Second"
push_group_array.append(id: 1, code: newCode, title: newTitle)
}
func loaddata()
{
print("loaddata")
guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song")
else
{
print("Invalid URL")
return
}
var urlData: NSData?
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data
{
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
{
DispatchQueue.main.async
{
urlData = data as NSData?
self.results = decodedResponse.results
print(self.results)
print(urlData ?? "urlData_Defaultvalue")
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You need to push the object rather than 3 values
push_group_array.append(push_group_row(id: 1, code: newCode, title: newTitle))

SwiftUI : difficulty with dictionary to define a result list of search

I'll try to do one Search View.
I would like to save the result in a dictionary in order to create a list of result but xCode show me this error :
Cannot assign through subscript: 'self' is immutable
My code :
import SwiftUI
struct SearchListView: View {
#State var search: String = "test"
var stringDictionary: Dictionary = [Int: String]()
var body: some View
{
NavigationView
{
ForEach(chapterData) { chapter in
ForEach(chapter.lines) { line in
HStack {
if (self.search == line.text) {
HStack {
stringDictionary[0] = line.text
}
}
}
}
}
}
}
}
struct SearchListView_Previews: PreviewProvider {
static var previews: some View {
SearchListView(search: "test")
}
}
struct Chapter: Codable, Identifiable {
let id:Int
let lines: [Line]
}
struct Line: Codable, Identifiable {
let id: Int
let text: String
}

SwiftUI Picker with Enum Source Is Not Enabled

I'm trying to understand the new SwiftUI picker style, especially with data from a source other than an array. I have built a picker with an enum. I first made a simple app with only the picker and associated enum. This works as expected.
Strangely, when I copy and paste that code into another app with other controls in the form, the picker seems to be inactive. I see it, but cannot click it.
Here's the first app (the picker works):
struct ContentView: View {
#State private var selectedVegetable = VegetableList.asparagus
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $selectedVegetable, label: Text("My Vegetables")) {
ForEach(VegetableList.allCases) { v in
Text(v.name).tag(v)
//use of tag makes no difference
}
}
}
}
.navigationBarTitle("Picker with Enum")
}
}
}
enum VegetableList: CaseIterable, Hashable, Identifiable {
case asparagus
case celery
case shallots
case cucumbers
var name: String {
return "\(self)".map {
$0.isUppercase ? " \($0)" : "\($0)" }.joined().capitalized
}
var id: VegetableList {self}
}
Here's the app with other controls (picker does not work).
struct Order {
var includeMustard = false
var includeMayo = false
var quantity: Int = 1
var avocadoStyle = PepperoniStyle.sliced
var vegetableType = VegetableType.none
var breadType = BreadType.wheat
}
struct OrderForm: View {
#State private var order = Order()
#State private var comment = "No Comment"
#State private var selectedVegetable = VegetableType.asparagus
#State private var selectedBread = BreadType.rye
func submitOrder() {}
var body: some View {
Form {
Text("Vegetable Ideas")
.font(.title)
.foregroundColor(.green)
Section {
Picker(selection: $selectedVegetable, label: Text("Vegetables")) {
ForEach(VegetableType.allCases) { v in
Text(v.name).tag(v)
}
}
Picker(selection: $selectedBread, label: Text("Bread")) {
ForEach(BreadType.allCases) { b in
Text(b.name).tag(b)
}
}
}
Toggle(isOn: $order.includeMustard) {
Text("Include Mustard")
}
Toggle(isOn: $order.includeMayo) {
Text("Include Mayonaisse")
}
Stepper(value: $order.quantity, in: 1...10) {
Text("Quantity: \(order.quantity)")
}
TextField("Say What?", text: $comment)
Button(action: submitOrder) {
Text("Order")
}
}
.navigationBarTitle("Picker in Form")
.padding()
}
}
enum PepperoniStyle {
case sliced
case crushed
}
enum BreadType: CaseIterable, Hashable, Identifiable {
case wheat, white, rye, sourdough, seedfeast
var name: String { return "\(self)".capitalized }
var id: BreadType {self}
}
enum VegetableType: CaseIterable, Hashable, Identifiable {
case none
case asparagus
case celery
case shallots
case cucumbers
var name: String {
return "\(self)".map {
$0.isUppercase ? " \($0)" : "\($0)" }.joined().capitalized
}
var id: VegetableType {self}
}
Xcode 11 Beta 7, Catalina Beta 7
There is no behavior difference between Preview and Simulator .I must be missing
something simple here. Any guidance would be appreciated.
I wrapped the Form in a NavigationView and the pickers now operate as expected. I need to research that once the documentation is more complete but perhaps this can help someone else.

Resources