Post

Replies

Boosts

Views

Activity

Deleting a Row in the List with Data from Realm
I have created a very simple sample project just to make my point using RealmSwift.. // ContentView.swift // import SwiftUI import RealmSwift struct ContentView: View { @StateObject var viewModel = ViewModel() var body: some View { NavigationView { VStack { Spacer() NavigationLink("Listing all meals") { ListView() .environmentObject(viewModel) } Spacer() } } } } // ListView.swift // import SwiftUI import RealmSwift struct ListView: View { @EnvironmentObject var viewModel: ViewModel @State var meals = [MealDB]() var body: some View { List { ForEach(meals) { meal in HStack { Text("\(meal.title)") .padding(.leading, 6.0) Spacer() Button { viewModel.model.delete(id: meal.id) } label: { Text("Delete") } .padding(.trailing, 6.0) .buttonStyle(.borderless) } .onDrag { return NSItemProvider() } } .onMove(perform: move(from:to:)) } .onAppear { updateData() } } func updateData() { meals.removeAll() // data from Realm database for mealItem in viewModel.mealItems {// <<<<<<<<<< meals.append(mealItem) } meals.sort { (($0).place < (($1).place)) } } } // ViewModel.swift // import Foundation import RealmSwift class ViewModel: ObservableObject { @Published var model = MealStore() var mealItems: Results<MealDB> { model.items } } final class MealStore: ObservableObject { var config: Realm.Configuration init() { config = Realm.Configuration() } var realm: Realm { return try! Realm(configuration: config) } var items: Results<MealDB> { realm.objects(MealDB.self) } } // MealDB.swift // import Foundation import RealmSwift class MealDB: Object, Identifiable { @objc dynamic var id = "" @objc dynamic var title = "" @objc dynamic var order = 0 @objc dynamic var place = 0 override class func primaryKey() -> String? { "id" } } ListView has a list of meals. Each row comes with a button that lets me delete the corresponding row. And the app will crash inside the updateData function. I have found out that the issue is the way how SwiftUI works and hangs on to the old set of data even after I tap the delete button. So a solution is to 'freeze up' the dataset. And the app won't crash when I tap the delete button. for mealItem in viewModel.mealItems.freeze() { ... } Now, my question is... Are there reasons for not freezing up the dataset? If there is no downside, how come MongoDB just doesn't tell us to do it when we use access a dataset in Realm? Thanks.
1
0
818
Sep ’22
Not Allowing Row Selection in List
In UIKit, it's just the matter of setting table view's allowsSelection to false if you don't want to allow selection. If each row has a button, it can still be clicked on. Can we do that in SwiftUI? I have the following simple SwiftUI project. import SwiftUI struct ContentView: View { @State private var fruits = ["Apple", "Banana", "Mango", "Watermelon", "Pineapple", "Strawberry", "Orange"] @State private var isEditable = true var body: some View { List { ForEach(fruits, id: \.self) { fruit in HStack { Text(fruit) .onDrag { return NSItemProvider() } Spacer() Button { print("Hello") } label: { Text("Tap me") } } } .onMove(perform: move) } .onTapGesture(perform: { return }) .listStyle(.plain) } func move(from source: IndexSet, to destination: Int) { fruits.move(fromOffsets: source, toOffset: destination) withAnimation { isEditable = false } } } The tap gesture prevents row interaction. So I won't even be able to tap the button. How can I disable row selection while allowing interaction inside the list row? List { } .onAppear { UITableView.appearance().allowsSelection = false UITableViewCell.appearance().selectionStyle = .none } The lines of code above don't work, either. Thanks.
1
0
2.3k
Aug ’22
NSItemProvider & DropDelegate - Shrinking Preview Picture
I have downloaded a sample project at raywenderlich.com (https://www.raywenderlich.com/22408716-drag-and-drop-editable-lists-tutorial-for-swiftui). I am working on a project involving DropDelegate. And I have a question with this project to make my point. In reference to the picture shown below, if I grab, drag and move Count Sheep, its preview picture will shrink. How could I prevent the preview picture from shrinking its size? struct ContentView: View { @EnvironmentObject private var todoList: TodoList @State private var isShowingAddTodoView = false @State private var editMode: EditMode = .inactive @State private var focusId: Int? func addTodo() { isShowingAddTodoView = true } var body: some View { NavigationView { VStack { FocusTodoView(focusId: focusId) .padding() .onDrop( of: [TodoItem.typeIdentifier], delegate: TodoDropDelegate(focusId: $focusId)) ScrollView { ActiveTodoView() CompletedTodoView() .disabled(editMode.isEditing) .onDrop(of: [TodoItem.typeIdentifier], isTargeted: nil) { itemProviders in for itemProvider in itemProviders { itemProvider.loadObject(ofClass: TodoItem.self) { todoItem, _ in guard let todoItem = todoItem as? TodoItem else { return } DispatchQueue.main.async { todoList.updateTodo(withId: todoItem.id, isCompleted: true) } } } return true } } .applyPlainListAppearance() .navigationBarTitle("Drag Todo") .toolbar { ToolbarItemGroup(placement: .navigationBarTrailing) { EditButton() Button(action: addTodo) { Image(systemName: "plus") } .disabled(editMode.isEditing) } } .environment(\.editMode, $editMode) .sheet(isPresented: $isShowingAddTodoView) { AddTodoView() } } } .navigationViewStyle(StackNavigationViewStyle()) } } I wish I had a simpler sample. That's the only sample I have been able to find. Anyway, I've been asking Google all day about "SwiftUI DropDelegate preview" with no luck. Thanks.
2
0
761
Aug ’22
Observing a Call from ObservableObject without onChange
I have a simple case as follows. class Monster: ObservableObject { static let shared = Monster() @Published var selectionChanged = false } struct ContentView: View { @ObservedObject var monster = Monster.shared @State private var isOn = false var body: some View { VStack { Button { monster.selectionChanged.toggle() } label: { Text("Tap me") } .padding(.vertical, 60.0) SecondView() } } } struct SecondView: View { @StateObject var monster = Monster.shared var body: some View { VStack { Text("Hello") }.onChange(of: monster.selectionChanged) { _ in print("GGGG") } } } So SecondView receives a call from Monster with through onChange.. Is there a simpler approach where SecondView receives a call without it? Thanks.
1
0
1.2k
Aug ’22
Files Selected with UIDocumentPickerViewController Ending Up in File Provider Storage [SwiftUI]
I often use security-scoped bookmarks when I develop a desktop application in Cocoa. This time, I need to use them in an iOS app, using SwiftUI framework. I don't quite remember the history, but I use UIDocumentPickerViewController through UIViewControllerRepresentable to let the user select a file. And I have a model where I save file name, file path, its bookmark (Data) with NSKeyedArchiver.. And everything goes well when I run the app in a simulator. Yet, FileManager says each file in the model does not exist. One of the path is something like the following. /private/var/mobile/Containers/Shared/AppGroup/749F05F0-12BC-40AC-B5C4-72571145C624/File Provider Storage/Test/somefile.txt Since it doesn't exist, I cannot even resolve it. How can I resolve the bookmark if a file ends up at the File Provider Storage folder? Do I need a special capability that I don't know about or something? Thanks.
1
0
664
Jul ’22
System requirements for Xcode 14
I'm a bit confused about the minimum macOS version required to run Xcode 14. I don't know what the minimum macOS version to run it. In the meantime, it seems that macOS 13 beta requires a Mac computer with the Apple silicon. As for Xcode 14 beta, its details say "Xcode 14 beta includes everything you need to create amazing apps for all Apple platforms. It includes SDKs for iOS 16, iPadOS 16, tvOS 16, watchOS 9, and macOS 13." What does that mean as far as macOS 13 is concerned? Do we need a Mac with the Apple silicon to run Xcode 14? Thanks.
1
0
8.1k
Jun ’22
Binding<String>, set, get?
I have three sets of Text and TextField. And I need to filter each TextField entry. I have gotten a function to filter the TextField entry from this website (https://zenn.dev/yorifuji/articles/swiftui-textfield-filter). Finally, I have the following lines of code. import SwiftUI struct ContentView: View { @State var username = "" @State var password = "" @State var tenantID = "" var body: some View { VStack { makeForm(label: "Username: ", placeHolder: "123456", text: $username) makeForm(label: "Password: ", placeHolder: "abcdefg", text: $password) makeForm(label: "Shop ID: ", placeHolder: "123456", text: $tenantID) }.padding(.horizontal, 40.0) } @ViewBuilder private func makeForm(label: String, placeHolder: String, text: Binding<String>) -> some View { HStack { let newText = Binding<String>( get: { text.wrappedValue }, set: { filter(value: $0) } ) Text(label) TextField(placeHolder, text: newText) } } func filter(value: String) -> String { let validCodes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" let sets = CharacterSet(charactersIn: validCodes) return String(value.unicodeScalars.filter(sets.contains).map(Character.init)) } } Well, I don't know how to use the Binding with get and set, which I believe is what I need. Yet, I get a warning at the following line. set: { filter(value: $0) } What I need to do is set the filtered value to each TextField. What am I doing wrong? Thanks.
6
0
1.4k
May ’22
Showing Multiple Instances of View and Showing Results from Them
I have the following lines of code to show multiple instances of View (MyTextView) import SwiftUI struct ContentView: View { @State var myTextViews = [MyTextView]() var body: some View { VStack { Button { } label: { Text("Show me your current text strings") }.padding(.vertical, 10.0) VStack { ForEach(0 ..< myTextViews.count, id: \.self) { _ in MyTextView() } } Button { myTextViews.append(MyTextView()) } label: { Text("Add me!") }.padding(.vertical, 10.0) } } } struct MyTextView: View { @State var text = "" var body: some View { ZStack { TextField("Enter some text", text: $text) }.padding(.horizontal, 50.0) } } According to the screenshot, I have three instances, each of which contains TextField. After I tap the top button (Show me your current...), I want to show the result from each TextField. How can I do that? Thanks.
5
0
1.2k
Apr ’22
Horizontally-Aligned TextField Wrap?
I have a @State variable with an array of strings with which to create instances of TextField. So far, I have the following lines of code. import SwiftUI struct ContentView: View { @State private var names: [String] = ["Jim Thorton", "Susan Murphy", "Tom O'Donnell", "Nancy Smith"] var body: some View { HStack { ForEach($names, id: \.self) { $name in TextField("", text: $name) .fixedSize() .padding(.horizontal, 20.0) .background(Color.orange.opacity(0.2)) } } } } I wonder if there is a simple way of aligning instances of TextField horizontally such that one that exceeds the screen width will go to the next line like the following picture? Thanks.
2
0
1.7k
Apr ’22
TextField Binding
I have an array of a model with just a single string with which I want to create instances of TextField. And I get an error for the TextField string binding. I know that is wrong. But how can fix it so that I can use textModel.name as a Binding? import SwiftUI struct ContentView: View { @State var textModels = [TextModel]() var body: some View { HStack { ForEach(textModels.indices, id: \.self) { index in let textModel = textModels[index] TextField("", text: textModel.name) // <----- Cannot convert value of type 'String' to expected argument type 'Binding<String>' } }.background(Color.green) .onAppear { textModels.append(TextModel(name: "Jim Thorton")) textModels.append(TextModel(name: "Susan Murphy")) textModels.append(TextModel(name: "Tom O'Donnell")) textModels.append(TextModel(name: "Nancy Smith")) } } } struct TextModel: Hashable { let name: String } Thanks.
3
0
1.1k
Apr ’22
Deleting a View Instance with the Tap of a Button
I have a simple project where I have a UUID string followed by a tap button as shown below. If one taps the Add me, the app will list a new instance of a View (KeywordRow). The following is what I have. import SwiftUI struct ContentView: View { @ObservedObject var monster: Monster var body: some View { VStack { Button { monster.items.append(Keyword()) } label: { Text("Add me!") }.padding(.vertical, 10.0) ForEach($monster.items) { item in KeywordRow(id: item.id) } } } } // MARK: - ObservableObject class Monster: ObservableObject { @Published var items = [Keyword]() } // MARK: - Keyword struct Keyword: Identifiable { var id = UUID() } struct KeywordRow: View { @Binding var id: UUID var body: some View { VStack { HStack { Text("ID: \(id)") Button { /* ------ Delete ------ */ } label: { Text("Delete") } } } } } My question is how I can let the app delete the corresponding instance when I tap the Delete button? I have an ObservedObject variable, which I haven't used. Thanks.
3
0
1.5k
Apr ’22
Showing a Constructor Dialog View with an ObservedObject Object
I'm trying to show a dialog over ContentView. The dialog view, ShowDialogView, has an ObservedObject object with name and properties. class User: ObservableObject { @Published var name = "" @Published var age: Int = 0 } struct ShowDialogView: View { @Binding var isPresented: Bool @ObservedObject var user: User /* @State var name = "" */ init(isPresented: Binding<Bool>, user: User) { self._isPresented = isPresented self.user = user.searchWord //_name = State(initialValue: "Kimberly") } var body: some View { VStack { ... ... }.onAppear { print("\(user.name)") } } } struct ContentView: View { @State var user = User() @State var showMe = true var body: some View { VStack { ... ... ShowDialogView(isPresented: showMe, user: user) } } } The dialog view will open with no problem. The problem that I have is that the user object doesn't deliver anything beyond default values. If I somehow set the name property to "Kimberly" before the dialog appears, the app will end up showing no value (""). Even if I try setting an initial value to the name property in the constructor, the app will still show an empty value. What am I doing wrong? I'm sorry I cannot give you a lot of details in the code above. Thank you.
1
0
447
Apr ’22
Getting an Updated Value Through @EnvironmentObject
I have a simple project as follows. import SwiftUI class GameSettings: ObservableObject { @Published var score: Int = 100 } struct ContentView: View { @StateObject var settings = GameSettings() var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { RightView().environmentObject(GameSettings()) .frame(width: geo.size.width / 2.0, height: geo.size.height) Spacer() } VStack { HStack { Spacer() Button { print("\(settings.score)") } label: { Text("Print") .font(.largeTitle) }.padding(.trailing, 40.0) } Spacer() } } } } } struct RightView: View { @EnvironmentObject var settings: GameSettings var body: some View { ZStack { Color.red Button { settings.score += 100 } label: { Text("Change") .font(.largeTitle) } }.environmentObject(settings) } } So the score is supposed to increase by 100 if I tap the button over the red area. And I want to print the latest value by tapping the Print button at the top-right corner. But it will remain at 100. What am I doing wrong? And can I achieve my goal without using an @ObservedObject variable? Thanks.
2
0
520
Mar ’22
Passing a Variable Between Two Unrelated Views Without Binding
My ContentView has one View (RightView) inside. Tapping the button over RightView, the app will pass a boolean value to ContentView. struct ContentView: View { @ObservedObject var monster: MonsterObservable var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { RightView(showMe: $monster.showDialog) .frame(width: geo.size.width, height: geo.size.height) } ShowDialogView(isShowing: $monster.showDialog) { } .frame(width: 500, height: 600, alignment: .center) .cornerRadius(10.0) } } } } struct RightView: View { @Binding var showMe: Bool var body: some View { ZStack { Color.red Button { showMe = true } label: { Text("Tap me") .font(.largeTitle) } } } } class MonsterObservable: ObservableObject { @Published var showDialog = false } struct ShowDialogView<Content: View>: View { @Binding var isShowing: Bool @ViewBuilder let content: () -> Content var body: some View { Group { if isShowing { ZStack { Color.brown VStack { Spacer() Button { isShowing = false } label: { Text("Close me") .font(.largeTitle) }.padding([.top, .bottom], 100.0) } } } } } } So the code above works. If I tap the button over RightView, a small dialog (ShowDialogView) will appear. Currently, ContentView and RightView are bound. That's not exactly what I need. How can I pass a boolean value from RightView to ContentView without Binding where ContentView is the following? struct ContentView: View { @ObservedObject var monster: MonsterObservable var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { RightView() .frame(width: geo.size.width, height: geo.size.height) } ShowDialogView(isShowing: $monster.showDialog) { } .frame(width: 500, height: 600, alignment: .center) .cornerRadius(10.0) } } } }
1
0
608
Mar ’22
Telling a View to show a Dialog from Another
I was quite active in writing code in SwiftUI several months ago. I've forgotten how to use an ObservedObject object to channel a variable between two Views. Anyway, I need to show a dialog over ContentView when I tap a button that is shown over another (RightView). The following is my code. // ContentView.swift // import SwiftUI class ObserveMonster: ObservableObject { @Published var showDialog = false } struct ContentView: View { @ObservedObject var observeManiac: ObserveMonster var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { LeftView() .frame(width: geo.size.width / 2.0, height: geo.size.height, alignment: .leading) RightView() .frame(width: geo.size.width / 2.0, height: geo.size.height, alignment: .trailing) } ShowDialogView(isShowing: observeManiac.showDialog) { } .frame(width: 500, height: 600, alignment: .center) .cornerRadius(10.0) } } } } struct ShowDialogView<Content: View>: View { let isShowing: Bool @ViewBuilder let content: () -> Content var body: some View { Group { if isShowing { Color.blue } } .animation(.default, value: isShowing) } } // RightView.swift // import SwiftUI struct RightView: View { @StateObject var observeManiac = ObserveMonster() var body: some View { ZStack { Color.red Button { observeManiac.showDialog.toggle() } label: { Text("Tap me") .font(.largeTitle) } } } } When I tap the button, the dialog (ShowDialogView) is no show. Does anybody now what I'm doing wrong? Thanks a million.
3
0
596
Mar ’22
Deleting a Row in the List with Data from Realm
I have created a very simple sample project just to make my point using RealmSwift.. // ContentView.swift // import SwiftUI import RealmSwift struct ContentView: View { @StateObject var viewModel = ViewModel() var body: some View { NavigationView { VStack { Spacer() NavigationLink("Listing all meals") { ListView() .environmentObject(viewModel) } Spacer() } } } } // ListView.swift // import SwiftUI import RealmSwift struct ListView: View { @EnvironmentObject var viewModel: ViewModel @State var meals = [MealDB]() var body: some View { List { ForEach(meals) { meal in HStack { Text("\(meal.title)") .padding(.leading, 6.0) Spacer() Button { viewModel.model.delete(id: meal.id) } label: { Text("Delete") } .padding(.trailing, 6.0) .buttonStyle(.borderless) } .onDrag { return NSItemProvider() } } .onMove(perform: move(from:to:)) } .onAppear { updateData() } } func updateData() { meals.removeAll() // data from Realm database for mealItem in viewModel.mealItems {// <<<<<<<<<< meals.append(mealItem) } meals.sort { (($0).place < (($1).place)) } } } // ViewModel.swift // import Foundation import RealmSwift class ViewModel: ObservableObject { @Published var model = MealStore() var mealItems: Results<MealDB> { model.items } } final class MealStore: ObservableObject { var config: Realm.Configuration init() { config = Realm.Configuration() } var realm: Realm { return try! Realm(configuration: config) } var items: Results<MealDB> { realm.objects(MealDB.self) } } // MealDB.swift // import Foundation import RealmSwift class MealDB: Object, Identifiable { @objc dynamic var id = "" @objc dynamic var title = "" @objc dynamic var order = 0 @objc dynamic var place = 0 override class func primaryKey() -> String? { "id" } } ListView has a list of meals. Each row comes with a button that lets me delete the corresponding row. And the app will crash inside the updateData function. I have found out that the issue is the way how SwiftUI works and hangs on to the old set of data even after I tap the delete button. So a solution is to 'freeze up' the dataset. And the app won't crash when I tap the delete button. for mealItem in viewModel.mealItems.freeze() { ... } Now, my question is... Are there reasons for not freezing up the dataset? If there is no downside, how come MongoDB just doesn't tell us to do it when we use access a dataset in Realm? Thanks.
Replies
1
Boosts
0
Views
818
Activity
Sep ’22
Not Allowing Row Selection in List
In UIKit, it's just the matter of setting table view's allowsSelection to false if you don't want to allow selection. If each row has a button, it can still be clicked on. Can we do that in SwiftUI? I have the following simple SwiftUI project. import SwiftUI struct ContentView: View { @State private var fruits = ["Apple", "Banana", "Mango", "Watermelon", "Pineapple", "Strawberry", "Orange"] @State private var isEditable = true var body: some View { List { ForEach(fruits, id: \.self) { fruit in HStack { Text(fruit) .onDrag { return NSItemProvider() } Spacer() Button { print("Hello") } label: { Text("Tap me") } } } .onMove(perform: move) } .onTapGesture(perform: { return }) .listStyle(.plain) } func move(from source: IndexSet, to destination: Int) { fruits.move(fromOffsets: source, toOffset: destination) withAnimation { isEditable = false } } } The tap gesture prevents row interaction. So I won't even be able to tap the button. How can I disable row selection while allowing interaction inside the list row? List { } .onAppear { UITableView.appearance().allowsSelection = false UITableViewCell.appearance().selectionStyle = .none } The lines of code above don't work, either. Thanks.
Replies
1
Boosts
0
Views
2.3k
Activity
Aug ’22
NSItemProvider & DropDelegate - Shrinking Preview Picture
I have downloaded a sample project at raywenderlich.com (https://www.raywenderlich.com/22408716-drag-and-drop-editable-lists-tutorial-for-swiftui). I am working on a project involving DropDelegate. And I have a question with this project to make my point. In reference to the picture shown below, if I grab, drag and move Count Sheep, its preview picture will shrink. How could I prevent the preview picture from shrinking its size? struct ContentView: View { @EnvironmentObject private var todoList: TodoList @State private var isShowingAddTodoView = false @State private var editMode: EditMode = .inactive @State private var focusId: Int? func addTodo() { isShowingAddTodoView = true } var body: some View { NavigationView { VStack { FocusTodoView(focusId: focusId) .padding() .onDrop( of: [TodoItem.typeIdentifier], delegate: TodoDropDelegate(focusId: $focusId)) ScrollView { ActiveTodoView() CompletedTodoView() .disabled(editMode.isEditing) .onDrop(of: [TodoItem.typeIdentifier], isTargeted: nil) { itemProviders in for itemProvider in itemProviders { itemProvider.loadObject(ofClass: TodoItem.self) { todoItem, _ in guard let todoItem = todoItem as? TodoItem else { return } DispatchQueue.main.async { todoList.updateTodo(withId: todoItem.id, isCompleted: true) } } } return true } } .applyPlainListAppearance() .navigationBarTitle("Drag Todo") .toolbar { ToolbarItemGroup(placement: .navigationBarTrailing) { EditButton() Button(action: addTodo) { Image(systemName: "plus") } .disabled(editMode.isEditing) } } .environment(\.editMode, $editMode) .sheet(isPresented: $isShowingAddTodoView) { AddTodoView() } } } .navigationViewStyle(StackNavigationViewStyle()) } } I wish I had a simpler sample. That's the only sample I have been able to find. Anyway, I've been asking Google all day about "SwiftUI DropDelegate preview" with no luck. Thanks.
Replies
2
Boosts
0
Views
761
Activity
Aug ’22
Observing a Call from ObservableObject without onChange
I have a simple case as follows. class Monster: ObservableObject { static let shared = Monster() @Published var selectionChanged = false } struct ContentView: View { @ObservedObject var monster = Monster.shared @State private var isOn = false var body: some View { VStack { Button { monster.selectionChanged.toggle() } label: { Text("Tap me") } .padding(.vertical, 60.0) SecondView() } } } struct SecondView: View { @StateObject var monster = Monster.shared var body: some View { VStack { Text("Hello") }.onChange(of: monster.selectionChanged) { _ in print("GGGG") } } } So SecondView receives a call from Monster with through onChange.. Is there a simpler approach where SecondView receives a call without it? Thanks.
Replies
1
Boosts
0
Views
1.2k
Activity
Aug ’22
Files Selected with UIDocumentPickerViewController Ending Up in File Provider Storage [SwiftUI]
I often use security-scoped bookmarks when I develop a desktop application in Cocoa. This time, I need to use them in an iOS app, using SwiftUI framework. I don't quite remember the history, but I use UIDocumentPickerViewController through UIViewControllerRepresentable to let the user select a file. And I have a model where I save file name, file path, its bookmark (Data) with NSKeyedArchiver.. And everything goes well when I run the app in a simulator. Yet, FileManager says each file in the model does not exist. One of the path is something like the following. /private/var/mobile/Containers/Shared/AppGroup/749F05F0-12BC-40AC-B5C4-72571145C624/File Provider Storage/Test/somefile.txt Since it doesn't exist, I cannot even resolve it. How can I resolve the bookmark if a file ends up at the File Provider Storage folder? Do I need a special capability that I don't know about or something? Thanks.
Replies
1
Boosts
0
Views
664
Activity
Jul ’22
System requirements for Xcode 14
I'm a bit confused about the minimum macOS version required to run Xcode 14. I don't know what the minimum macOS version to run it. In the meantime, it seems that macOS 13 beta requires a Mac computer with the Apple silicon. As for Xcode 14 beta, its details say "Xcode 14 beta includes everything you need to create amazing apps for all Apple platforms. It includes SDKs for iOS 16, iPadOS 16, tvOS 16, watchOS 9, and macOS 13." What does that mean as far as macOS 13 is concerned? Do we need a Mac with the Apple silicon to run Xcode 14? Thanks.
Replies
1
Boosts
0
Views
8.1k
Activity
Jun ’22
Binding<String>, set, get?
I have three sets of Text and TextField. And I need to filter each TextField entry. I have gotten a function to filter the TextField entry from this website (https://zenn.dev/yorifuji/articles/swiftui-textfield-filter). Finally, I have the following lines of code. import SwiftUI struct ContentView: View { @State var username = "" @State var password = "" @State var tenantID = "" var body: some View { VStack { makeForm(label: "Username: ", placeHolder: "123456", text: $username) makeForm(label: "Password: ", placeHolder: "abcdefg", text: $password) makeForm(label: "Shop ID: ", placeHolder: "123456", text: $tenantID) }.padding(.horizontal, 40.0) } @ViewBuilder private func makeForm(label: String, placeHolder: String, text: Binding<String>) -> some View { HStack { let newText = Binding<String>( get: { text.wrappedValue }, set: { filter(value: $0) } ) Text(label) TextField(placeHolder, text: newText) } } func filter(value: String) -> String { let validCodes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" let sets = CharacterSet(charactersIn: validCodes) return String(value.unicodeScalars.filter(sets.contains).map(Character.init)) } } Well, I don't know how to use the Binding with get and set, which I believe is what I need. Yet, I get a warning at the following line. set: { filter(value: $0) } What I need to do is set the filtered value to each TextField. What am I doing wrong? Thanks.
Replies
6
Boosts
0
Views
1.4k
Activity
May ’22
Showing Multiple Instances of View and Showing Results from Them
I have the following lines of code to show multiple instances of View (MyTextView) import SwiftUI struct ContentView: View { @State var myTextViews = [MyTextView]() var body: some View { VStack { Button { } label: { Text("Show me your current text strings") }.padding(.vertical, 10.0) VStack { ForEach(0 ..< myTextViews.count, id: \.self) { _ in MyTextView() } } Button { myTextViews.append(MyTextView()) } label: { Text("Add me!") }.padding(.vertical, 10.0) } } } struct MyTextView: View { @State var text = "" var body: some View { ZStack { TextField("Enter some text", text: $text) }.padding(.horizontal, 50.0) } } According to the screenshot, I have three instances, each of which contains TextField. After I tap the top button (Show me your current...), I want to show the result from each TextField. How can I do that? Thanks.
Replies
5
Boosts
0
Views
1.2k
Activity
Apr ’22
Horizontally-Aligned TextField Wrap?
I have a @State variable with an array of strings with which to create instances of TextField. So far, I have the following lines of code. import SwiftUI struct ContentView: View { @State private var names: [String] = ["Jim Thorton", "Susan Murphy", "Tom O'Donnell", "Nancy Smith"] var body: some View { HStack { ForEach($names, id: \.self) { $name in TextField("", text: $name) .fixedSize() .padding(.horizontal, 20.0) .background(Color.orange.opacity(0.2)) } } } } I wonder if there is a simple way of aligning instances of TextField horizontally such that one that exceeds the screen width will go to the next line like the following picture? Thanks.
Replies
2
Boosts
0
Views
1.7k
Activity
Apr ’22
TextField Binding
I have an array of a model with just a single string with which I want to create instances of TextField. And I get an error for the TextField string binding. I know that is wrong. But how can fix it so that I can use textModel.name as a Binding? import SwiftUI struct ContentView: View { @State var textModels = [TextModel]() var body: some View { HStack { ForEach(textModels.indices, id: \.self) { index in let textModel = textModels[index] TextField("", text: textModel.name) // <----- Cannot convert value of type 'String' to expected argument type 'Binding<String>' } }.background(Color.green) .onAppear { textModels.append(TextModel(name: "Jim Thorton")) textModels.append(TextModel(name: "Susan Murphy")) textModels.append(TextModel(name: "Tom O'Donnell")) textModels.append(TextModel(name: "Nancy Smith")) } } } struct TextModel: Hashable { let name: String } Thanks.
Replies
3
Boosts
0
Views
1.1k
Activity
Apr ’22
Deleting a View Instance with the Tap of a Button
I have a simple project where I have a UUID string followed by a tap button as shown below. If one taps the Add me, the app will list a new instance of a View (KeywordRow). The following is what I have. import SwiftUI struct ContentView: View { @ObservedObject var monster: Monster var body: some View { VStack { Button { monster.items.append(Keyword()) } label: { Text("Add me!") }.padding(.vertical, 10.0) ForEach($monster.items) { item in KeywordRow(id: item.id) } } } } // MARK: - ObservableObject class Monster: ObservableObject { @Published var items = [Keyword]() } // MARK: - Keyword struct Keyword: Identifiable { var id = UUID() } struct KeywordRow: View { @Binding var id: UUID var body: some View { VStack { HStack { Text("ID: \(id)") Button { /* ------ Delete ------ */ } label: { Text("Delete") } } } } } My question is how I can let the app delete the corresponding instance when I tap the Delete button? I have an ObservedObject variable, which I haven't used. Thanks.
Replies
3
Boosts
0
Views
1.5k
Activity
Apr ’22
Showing a Constructor Dialog View with an ObservedObject Object
I'm trying to show a dialog over ContentView. The dialog view, ShowDialogView, has an ObservedObject object with name and properties. class User: ObservableObject { @Published var name = "" @Published var age: Int = 0 } struct ShowDialogView: View { @Binding var isPresented: Bool @ObservedObject var user: User /* @State var name = "" */ init(isPresented: Binding<Bool>, user: User) { self._isPresented = isPresented self.user = user.searchWord //_name = State(initialValue: "Kimberly") } var body: some View { VStack { ... ... }.onAppear { print("\(user.name)") } } } struct ContentView: View { @State var user = User() @State var showMe = true var body: some View { VStack { ... ... ShowDialogView(isPresented: showMe, user: user) } } } The dialog view will open with no problem. The problem that I have is that the user object doesn't deliver anything beyond default values. If I somehow set the name property to "Kimberly" before the dialog appears, the app will end up showing no value (""). Even if I try setting an initial value to the name property in the constructor, the app will still show an empty value. What am I doing wrong? I'm sorry I cannot give you a lot of details in the code above. Thank you.
Replies
1
Boosts
0
Views
447
Activity
Apr ’22
Getting an Updated Value Through @EnvironmentObject
I have a simple project as follows. import SwiftUI class GameSettings: ObservableObject { @Published var score: Int = 100 } struct ContentView: View { @StateObject var settings = GameSettings() var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { RightView().environmentObject(GameSettings()) .frame(width: geo.size.width / 2.0, height: geo.size.height) Spacer() } VStack { HStack { Spacer() Button { print("\(settings.score)") } label: { Text("Print") .font(.largeTitle) }.padding(.trailing, 40.0) } Spacer() } } } } } struct RightView: View { @EnvironmentObject var settings: GameSettings var body: some View { ZStack { Color.red Button { settings.score += 100 } label: { Text("Change") .font(.largeTitle) } }.environmentObject(settings) } } So the score is supposed to increase by 100 if I tap the button over the red area. And I want to print the latest value by tapping the Print button at the top-right corner. But it will remain at 100. What am I doing wrong? And can I achieve my goal without using an @ObservedObject variable? Thanks.
Replies
2
Boosts
0
Views
520
Activity
Mar ’22
Passing a Variable Between Two Unrelated Views Without Binding
My ContentView has one View (RightView) inside. Tapping the button over RightView, the app will pass a boolean value to ContentView. struct ContentView: View { @ObservedObject var monster: MonsterObservable var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { RightView(showMe: $monster.showDialog) .frame(width: geo.size.width, height: geo.size.height) } ShowDialogView(isShowing: $monster.showDialog) { } .frame(width: 500, height: 600, alignment: .center) .cornerRadius(10.0) } } } } struct RightView: View { @Binding var showMe: Bool var body: some View { ZStack { Color.red Button { showMe = true } label: { Text("Tap me") .font(.largeTitle) } } } } class MonsterObservable: ObservableObject { @Published var showDialog = false } struct ShowDialogView<Content: View>: View { @Binding var isShowing: Bool @ViewBuilder let content: () -> Content var body: some View { Group { if isShowing { ZStack { Color.brown VStack { Spacer() Button { isShowing = false } label: { Text("Close me") .font(.largeTitle) }.padding([.top, .bottom], 100.0) } } } } } } So the code above works. If I tap the button over RightView, a small dialog (ShowDialogView) will appear. Currently, ContentView and RightView are bound. That's not exactly what I need. How can I pass a boolean value from RightView to ContentView without Binding where ContentView is the following? struct ContentView: View { @ObservedObject var monster: MonsterObservable var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { RightView() .frame(width: geo.size.width, height: geo.size.height) } ShowDialogView(isShowing: $monster.showDialog) { } .frame(width: 500, height: 600, alignment: .center) .cornerRadius(10.0) } } } }
Replies
1
Boosts
0
Views
608
Activity
Mar ’22
Telling a View to show a Dialog from Another
I was quite active in writing code in SwiftUI several months ago. I've forgotten how to use an ObservedObject object to channel a variable between two Views. Anyway, I need to show a dialog over ContentView when I tap a button that is shown over another (RightView). The following is my code. // ContentView.swift // import SwiftUI class ObserveMonster: ObservableObject { @Published var showDialog = false } struct ContentView: View { @ObservedObject var observeManiac: ObserveMonster var body: some View { GeometryReader { geo in ZStack { HStack(spacing: 0.0) { LeftView() .frame(width: geo.size.width / 2.0, height: geo.size.height, alignment: .leading) RightView() .frame(width: geo.size.width / 2.0, height: geo.size.height, alignment: .trailing) } ShowDialogView(isShowing: observeManiac.showDialog) { } .frame(width: 500, height: 600, alignment: .center) .cornerRadius(10.0) } } } } struct ShowDialogView<Content: View>: View { let isShowing: Bool @ViewBuilder let content: () -> Content var body: some View { Group { if isShowing { Color.blue } } .animation(.default, value: isShowing) } } // RightView.swift // import SwiftUI struct RightView: View { @StateObject var observeManiac = ObserveMonster() var body: some View { ZStack { Color.red Button { observeManiac.showDialog.toggle() } label: { Text("Tap me") .font(.largeTitle) } } } } When I tap the button, the dialog (ShowDialogView) is no show. Does anybody now what I'm doing wrong? Thanks a million.
Replies
3
Boosts
0
Views
596
Activity
Mar ’22