How do I create another unique view for each device? - view

How do I create another view when the user chooses a device ? For each device, the view will not be the same because the information given will not be the same ( custom view )
Thank you to put me on the track.
Canvas image
struct ContentView: View {
var body: some View {
NavigationView {
List(Ios, children: \.sousMenuIos) { item in
HStack {
Image(item.image)
.resizable()
.scaledToFit()
.frame(width: 60, height: 60)
Text(item.name)
.font(.system(.title3, design: .rounded))
.bold()
}
}
.navigationTitle("Jailbreak")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()

You need to wrap your list label in a NavigationLink and pass the item to the costum view that you want. here is a working example with dummy data.
struct ListItems: View {
var body: some View {
NavigationView {
List(iOS.previewData) { item in
NavigationLink(destination: CostumView(text: item.name)){
HStack {
Image(systemName: item.image)
.resizable()
.scaledToFit()
.frame(width: 60, height: 60)
Text(item.name)
.font(.system(.title3, design: .rounded))
.bold()
}
}
}
.navigationTitle("Jailbreak")
}
}
}
struct CostumView: View {
var text: String
var body: some View{
Text(text)
}
}
struct ListItems_Previews: PreviewProvider {
static var previews: some View {
ListItems()
}
}
struct iOS: Identifiable {
var id = UUID()
var image: String = ""
var name: String
static let previewData = [
iOS(image: "phone", name: "iPhone 8"),
iOS(image: "phone", name: "iPhone X")
]
}

Related

Updating the contents of an array from a different view

I'm writing a macOS app in Swiftui, for Big Sur and newer. It's a three pane navigationview app, where the left most pane has the list of options (All Notes in this case), the middle pane is a list of the actual items (title and date), and the last one is a TextEditor where the user adds text.
Each pane is a view that calls the the next view via a NavigationLink. Here's the basic code for that.
struct NoteItem: Codable, Hashable, Identifiable {
let id: Int
var text: String
var date = Date()
var dateText: String {
dateFormatter.dateFormat = "EEEE, MMM d yyyy, h:mm a"
return dateFormatter.string(from: date)
}
var tags: [String] = []
}
struct ContentView: View {
#State var selection: Set<Int> = [0]
var body: some View {
NavigationView {
List(selection: self.$selection) {
NavigationLink(destination: AllNotes()) {
Label("All Notes", systemImage: "doc.plaintext")
}
.tag(0)
}
.listStyle(SidebarListStyle())
.frame(minWidth: 100, idealWidth: 150, maxWidth: 200, maxHeight: .infinity)
Text("Select a note...")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
struct AllNotes: View {
#State var items: [NoteItem] = {
guard let data = UserDefaults.standard.data(forKey: "notes") else { return [] }
if let json = try? JSONDecoder().decode([NoteItem].self, from: data) {
return json
}
return []
}()
#State var noteText: String = ""
var body: some View {
NavigationView {
List(items) { item in
NavigationLink(destination: NoteView()) {
VStack(alignment: .leading) {
Text(item.text.components(separatedBy: NSCharacterSet.newlines).first!)
Text(item.dateText).font(.body).fontWeight(.light)
}
.padding(.vertical, 8)
}
}
.listStyle(InsetListStyle())
Text("Select a note...")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.navigationTitle("A title")
.toolbar {
ToolbarItem(placement: .navigation) {
Button(action: {
NewNote()
}) {
Image(systemName: "square.and.pencil")
}
}
}
}
struct NoteView: View {
#State var text: String = ""
var body: some View {
HStack {
VStack(alignment: .leading) {
TextEditor(text: $text).padding().font(.body)
.onChange(of: text, perform: { value in
print("Value of text modified to = \(text)")
})
Spacer()
}
Spacer()
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.white)
}
}
When I create a new note, how can I save the text the user added on the TextEditor in NoteView in the array loaded in AllNotes so I could save the new text? Ideally there is a SaveNote() function that would happen on TextEditor .onChange. But again, given that the array lives in AllNotes, how can I update it from other views?
Thanks for the help. Newbie here!
use EnvironmentObject in App
import SwiftUI
#main
struct NotesApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(DataModel())
}
}
}
now DataModel is a class conforming to ObservableObject
import SwiftUI
final class DataModel: ObservableObject {
#AppStorage("notes") public var notes: [NoteItem] = []
}
any data related stuff should be done in DataModel not in View, plus you can access it and update it from anywhere, declare it like this in your ContentView or any child View
NoteView
import SwiftUI
struct NoteView: View {
#EnvironmentObject private var data: DataModel
var note: NoteItem
#State var text: String = ""
var body: some View {
HStack {
VStack(alignment: .leading) {
TextEditor(text: $text).padding().font(.body)
.onChange(of: text, perform: { value in
guard let index = data.notes.firstIndex(of: note) else { return }
data.notes[index].text = value
})
Spacer()
}
Spacer()
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.white)
.onAppear() {
print(data.notes.count)
}
}
}
AppStorage is the better way to use UserDefaults but AppStorage does not work with custom Objects yet (I think it does for iOS 15), so you need to add this extension to make it work.
import SwiftUI
struct NoteItem: 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 tags: [String] = []
}
extension Array: RawRepresentable where Element: Codable {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode([Element].self, from: data)
else {
return nil
}
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let result = String(data: data, encoding: .utf8)
else {
return "[]"
}
return result
}
}
Now I changed AllNotes view to work with new changes
struct AllNotes: View {
#EnvironmentObject private var data: DataModel
#State var noteText: String = ""
var body: some View {
NavigationView {
List(data.notes) { note in
NavigationLink(destination: NoteView(note: note)) {
VStack(alignment: .leading) {
Text(note.text.components(separatedBy: NSCharacterSet.newlines).first!)
Text(note.dateText).font(.body).fontWeight(.light)
}
.padding(.vertical, 8)
}
}
.listStyle(InsetListStyle())
Text("Select a note...")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.navigationTitle("A title")
.toolbar {
ToolbarItem(placement: .navigation) {
Button(action: {
data.notes.append(NoteItem(id: UUID(), text: "New Note", date: Date(), tags: []))
}) {
Image(systemName: "square.and.pencil")
}
}
}
}
}

Send data to next view - SwiftUI

So I have been trying to get a simple pass of data working with SwiftUI.
Basically the below script prints out a list of items (in a HStack) I then have each one linked to our Podcast() view.
What I am trying to do is pass through the podcast name to the next view. How do I achieve
this? As all the examples are about int which I am not using am using a String.
import SwiftUI
import RemoteImage
struct ContentView: View {
#State private var showAlert = false
#State var posts: [Program] = []
var body: some View {
NavigationView {
if posts.isEmpty {
Text("Loading")
} else {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .bottom, spacing: 10) {
ForEach(posts) { post in
//return
NavigationLink(destination: Podcasts()){
RemoteImage(type: .url(URL(string:post.icon)!), errorView: { error in
Text(error.localizedDescription)
}, imageView: { image in
image
.resizable()
.renderingMode(.original)
/* .clipShape(Circle())
.shadow(radius: 10)
.overlay(Circle().stroke(Color.red, lineWidth: 5))*/
.aspectRatio(contentMode: .fit)
.frame(width:200, height:200)
}, loadingView: {
Text("Loading ...")
})
}
}
}.frame(height: 200)
}.frame(height: 200)
}
}.onAppear {
Api().getPosts { (posts) in
self.posts = posts
}
}.navigationBarTitle(Text("Home"))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The podcast View
import SwiftUI
struct Podcasts: View {
var body: some View {
NavigationView{
Text("Hello")
}.navigationBarTitle(Text("Podcast"))
}
}
struct Podcasts_Previews: PreviewProvider {
static var previews: some View {
Podcasts()
}
}
Pass post as constructor argument, like
ForEach(posts) { post in
//return
NavigationLink(destination: Podcasts(post: post)){
so now
struct Podcasts: View {
let post: Program
var body: some View {
// !! DON'T ADD SECOND NAVIGATION VIEW IN STACK
// !! - THERE MUST BE ONLY ONE
Text(post.name)
.navigationBarTitle(Text("Podcast"))
}
}

In a MacOS App using SwiftUI, how to modify the default blue background of a selected NavigationLink nested in a list?

Good day all. In a MacOS App using SwiftUI, how to modify the default blue background of a selected NavigationLink nested in a list? The list is inside a NavigationView. I could not find the solution here. What would be the code to add to the following basic exemple: Two TextView listed, and if we click on the TextView we display the correspondant View.
ContentView.swift:
import SwiftUI
struct ContentView: View {
#State var selection: Int?
var body: some View {
HStack() {
NavigationView {
List () {
NavigationLink(destination: FirstView(), tag: 0, selection: self.$selection) {
Text("Click Me To Display The First View")
} // End Navigation Link
NavigationLink(destination: SecondView(), tag: 1, selection: self.$selection) {
Text("Click Me To Display The Second View")
} // End Navigation Link
} // End list
.frame(minWidth: 350, maxWidth: 350)
.onAppear {
self.selection = 0
}
} // End NavigationView
.listStyle(SidebarListStyle())
.frame(maxWidth: .infinity, maxHeight: .infinity)
} // End HStack
} // End some View
} // End ContentView
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
FirstView.swift:
import SwiftUI
struct FirstView: View {
var body: some View {
Text("(1) Hello, I am the first view")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
SecondView.swift:
import SwiftUI
struct SecondView: View {
var body: some View {
Text("(2) Hello, I am the second View")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
Here is the result if we click on the first row... the background is blue when selected! How to change this default color? Thanks in advance for your help.
the following code is one option to achieve what you want:
struct ContentView: View {
#State var selection: Int? = 0
#State var pressed: Int? = 0
init() {
UITableViewCell.appearance().selectionStyle = .none
UITableView.appearance().backgroundColor = UIColor.clear
}
var body: some View {
var theBinding = Binding(
get: { self.selection },
set: {
self.selection = $0
self.pressed = $0 == nil ? self.pressed : $0!
})
return HStack() {
NavigationView {
List {
NavigationLink(destination: FirstView(), tag: 0, selection: theBinding) {
Text("Click Me To Display The First View")
}.listRowBackground(self.pressed == 0 ? Color.red : Color.green)
NavigationLink(destination: SecondView(), tag: 1, selection: theBinding) {
Text("Click Me To Display The Second View")
}.listRowBackground(self.pressed == 1 ? Color.red : Color.green)
}.frame(minWidth: 350, maxWidth: 350)
.onAppear { self.pressed = 0 }
}.listStyle(SidebarListStyle())
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}

SwiftUI: How to replace a View with another in MacOS

I want to replace a View with another when a Button is pressed in SwiftUI on MacOS (AppKit not Catalyst).
I tried with a NavigationLink like this
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink( destination: Text("DESTINATIONVIEW").frame(maxWidth: .infinity, maxHeight: .infinity) ,
label: {Text("Next")} )
}.frame(width: 500.0, height: 500.0)
}
}
The Destination View is presented like in iPadOS, like a Master-Detail Presentation right of the Source View.
What I want, is to replace the SourceView with the Destination (almost like in iOS)
Another approach was to switch the presented view with a bool variable
struct MasterList: View
{
private let names = ["Frank", "John", "Tom", "Lisa"]
#State var showDetail: Bool = false
#State var selectedName: String = ""
var body: some View
{
VStack
{
if (showDetail)
{ DetailViewReplace(showDetail:$showDetail, text: "\(selectedName)" )
} else
{
List()
{
ForEach(names, id: \.self)
{ name in
Button(action:
{
self.showDetail.toggle()
self.selectedName = name
})
{ Text("\(name)")}
.buttonStyle( LinkButtonStyle() )
}
}.listStyle( SidebarListStyle())
}
}
}
}
struct DetailViewReplace: View {
#Binding var showDetail: Bool
let text: String
var body: some View
{
VStack
{
Text(text)
.frame(maxWidth: .infinity, maxHeight: .infinity)
Button(action:
{ self.showDetail.toggle()
})
{ Text("Return")
}
}
}
}
But that seems quite cumbersome for me if dealing with many views.
Is there a best practice to do that?

MacOS-style List with Plus and Minus buttons

How can I do something like that in SwiftUI?
Reckon this view is built in Cocoa, since I can't even layout List and GroupBox properly: strange border appears.
There is no Table view in SwiftUI, there is no NSSegmentedControl.
This is the code I got so far:
import SwiftUI
struct DetailView: View {
let text: String
var body: some View {
GroupBox {
Text(text)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.padding(.leading, 20)
.frame(width:300, height:300)
}
}
struct ContentView: View {
private let names = ["One", "Two", "Three"]
#State private var selection: String? = "One"
var body: some View {
NavigationView {
List(selection: $selection) {
Section(header:
Text("Header")) {
ForEach(names, id: \.self) { name in
NavigationLink(destination: DetailView(text: name)) {
Text(name)
}
}
}
}.frame(width: 200, height: 300).padding(10).border(Color.green, width: 0)
DetailView(text: self.selection ?? "none selected")
}.padding(10)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
import AppKit
struct ContentView: View {
var body: some View {
HStack(spacing: 20) {
PrinterPicker()
.frame(width: 160)
PrinterDetail()
.frame(width: 320)
} //
.padding()
}
}
struct PrinterPicker: View {
var body: some View {
VStack(spacing: 0) {
PrinterList()
PrinterListToolbar()
} //
.border(Color(NSColor.gridColor), width: 1)
}
}
struct PrinterList: View {
var body: some View {
List {
Text("Printer 1")
.font(Font.system(size: 15))
Text("Printer 2")
.font(Font.system(size: 15))
}
}
}
struct PrinterListToolbar: View {
var body: some View {
HStack(spacing: 0) {
ListButton(imageName: NSImage.addTemplateName)
Divider()
ListButton(imageName: NSImage.removeTemplateName)
Divider()
Spacer()
} //
.frame(height: 20)
}
}
struct ListButton: View {
var imageName: String
var body: some View {
Button(action: {}) {
Image(nsImage: NSImage(named: imageName)!)
.resizable()
} //
.buttonStyle(BorderlessButtonStyle())
.frame(width: 20, height: 20)
}
}
struct PrinterDetail: View {
var body: some View {
HStack {
Spacer()
VStack {
Spacer()
Text("No printers are available.")
Text("Click Add (+) to set up a printer.")
Spacer()
}
Spacer()
} //
.font(Font.system(size: 15))
.background(Color(
NSColor.unemphasizedSelectedContentBackgroundColor))
.cornerRadius(6)
.overlay(
RoundedRectangle(cornerRadius: 6)
.stroke(lineWidth: 1)
.foregroundColor(Color(NSColor.gridColor)))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Resources