Hello everyone,
I wanted to double check with the UI Framework team to see if there's a mistake in my code or if there's some sort of regression.
My goal is to have a user input text without any automatic modification of said text, namely remove auto-capitalization and auto-correct.
//
// ContentView.swift
// TextInputTest
//
import SwiftUI
struct ContentView: View {
@State var text: String = "Enter some text here!"
var body: some View {
VStack {
TextEditor(text: $text)
.autocorrectionDisabled(true)
.textInputAutocapitalization(.never)
.font(Font.custom("SF Mono", size: 30))
.monospaced()
.padding(20)
}
.padding()
}
}
However, when typing the following: "This is a sentence" followed by a few spaces, a dot will automatically be inserted, making the string become: "This is a sentence.".
Reproduced on: VisionOS 2.0 beta 3 (22N5277g)
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Is there a way to use NSPathControl or something equivalent in SwiftUI on Mac?
Dear all,
I am experiencing some problems with the Drag Gesture in VisionOS. Typically, this gesture involves the user pinching an entity or, more commonly, a window, and moving/dragging it around. However, this is not always the case for entities (3D models) placed in the environment. It appears that the user can both pinch and drag and/or move the entity with their bare hands.
In the latter case, the onChange cycle doesn't always end if the user keeps their hands near the object, causing it to keep moving even if that is not what the user intends. This also occurs when the user is no longer hovering over that entity. Larger entities, more so than those in the demo "TransformingRealityKitEntitiesUsingGestures," close to the user seem to become attached to their hands, causing the gesture to continue indefinitely. Entities often move to unintended positions.
I believe that these two different behaviors within the same gesture container are intrinsically different: one involves pinching and dragging, while the other involves enabling hands physics, and it should be easy to distinguish between the two.
How can we correctly address this situation?
Thank you for your assistance
Hello!
I'm building a Countdown Timer for the Dynamic Island using a Live Activity.
I have two issues for which I can't find any solution:
We want to display the time in the "X minutes" format, like in this example. I went through the forum but all the answers were wrong, because they were using a Text(:format) which never updates in the live activity, or a Text(:timerInterval) which we can't format.
I want the Live Activity to end once the timer gets to zero. I found this staleDate parameter that I thought would helped, but is actually only adding loaders on my design once the date is reached. I tried to implement a solution like the answer of this post, but the if (context.isStale) {...} part is never being rendered. It also looks like the stale sate gets activated only when the app is focus again.
I tried several fixes, went through a lot of forum and posts, but I can't find any solution.
Thanks!
I have backend API caller file that retrieves and displays unwrapped JSON data via URLRequest(). All the data is printed to my console when I build the project but it's not being displayed in the actual UI of my iOS simulator.
I have a class in my ContentView that updates the UI and filters the extracted fields shown here below:
class NotionCall: ObservableObject {
@Published var extractedContent: [BlockBody.Block] = []
func makeAPIRequest() {
makeRequest { results in
let extractedData = results.map { block -> BlockBody.Block in
var extractedBlock = block
extractedBlock.ExtractedFields = block.paragraph?.textFields.compactMap { textField in
textField.PlainText ?? textField.RichText ?? textField.content //iterate over PlainText, RichText, and Content fields and return the non nill values
} ?? [] //validate objects even if they are nil
return extractedBlock
}
DispatchQueue.main.async {
self.extractedContent = extractedData
}
}
}
}
@StateObject var NotionCaller = NotionCall() //manage lifecycle of instance
And then below here is my SwiftUI structure that contains List(NotionCaller.extractedContent) { block in ForEach(block.ExtractedFields, id: \.self) { field in Text(field) meant to display the extracted data to the UI:
var body: some View {
NavigationStack {
ZStack {
List(NotionCaller.extractedContent) { block in
ForEach(block.ExtractedFields, id: \.self) { field in
Text(field)
}
}
ZStack {
Color(hex: "#f9f9f9")
.ignoresSafeArea()
VStack {
TextField(" Search keywords", text: $searchKeywords) //change font later
.frame(height: 48)
.overlay(RoundedRectangle(cornerRadius: 30).strokeBorder(style: StrokeStyle()))
.foregroundColor(.white)
.background(.white)
.cornerRadius(30)
.padding()
.scaledToFit()
.frame(maxHeight: .infinity, alignment: .top)
}
VStack {
Spacer()
Divider()
.padding()
HStack {
Button(action: { //add functionality later
}) {
Image("menuButton")
.frame(alignment: .bottom)
.padding(.horizontal, 42)
Spacer()
}
HStack {
Button(action: { //add functionality later
}) {
Image("notificationButton")
.frame(alignment: .leading)
.padding(.leading, 30)
Spacer()
}
}
HStack {
Button(action: {
}) {
Image("notionImportButton")
.frame( alignment: .trailing)
.padding(.horizontal)
.padding(.horizontal)
}
}
}
.onAppear {
NotionCaller.makeAPIRequest()
}
}
}
}
}
}
}
In the first Xcode 16 beta, none of my SwiftUI previews work - they all just crash on start up.
Has anybody run into this and found a workaround? Have tried all the usual steps of cleaning the project/restarting Xcode.
I found a regression in Apple Vision OS 2.0 beta 3 (22N5277g).
Previously, it was possible to trigger the .onDelete swipe gesture on a List/ForEach with a virtual mouse (i.e. remote desktop), however this is no longer possible (a finger pinch still works).
Sample code to reproduce the issue:
//
// ContentView.swift
// TextInputTest
//
import SwiftUI
struct ListElement: Identifiable {
let id = UUID()
let content: String
}
struct ContentView: View {
@State var list = [
ListElement(content: "a"),
ListElement(content: "b"),
ListElement(content: "c")
]
var body: some View {
List {
ForEach(list) { element in
Text(element.content)
}
.onDelete { _ in
// No-op.
}
}
}
}
With iOS 18, when you tint Home Screen, the widgets also need to pick up the tint. How do you detect this within SwiftUI?
I didn't see WWDC24 sessions addressing this.
Task:
A child view should show depending on a boolean flag the corresponding view. The flag is calculated from a model which is given by parent view.
Problem:
The flag is false in init, which is correct. However in body it's true, which is incorrect. Why value in body isn't consistent to init? Is there a race condition? The child view's is rendered thrice, that's another issue, but flag is in init and body as described before.
Parent view looks like this:
struct ParentView: View {
private var groupedItems: [GroupedItems] = []
init(items: [Item]) {
Dictionary(grouping: items) { $0.category.name }
.forEach {
let groupedItems = GroupedItems(categoryName: $0.key, items: $0.value)
self.groupedItems.append(groupedItems)
}
}
var body: some View {
ChildView(groupedItems)
}
}
Child view looks like this:
struct ChildView: View {
@State private var showItems: Bool
init(_ groupedItems: GroupedItems) {
self._showItems = State(initialValue: !groupedItems.completed)
}
var body: some View {
if showItems {
AView()
} else {
BView()
}
}
}
Model looks like this:
@Model
final class Item: Identifiable {
@Attribute(.unique) public var id: String
public var name: String
public var completed = false
}
struct GroupedItems {
var categoryName: String
var items: [Item]
var completed: Bool {
items.filter { !$0.completed }.isEmpty
}
}
Hi everyone,
I’m having an issue with SwiftUI where my entire Section becomes clickable, instead of just the “Edit profile” button. Here’s my code:
VStack(alignment: .center) {
KFImage(authManager.user?.photoURL)
.resizable()
.scaledToFill()
.frame(width: 80, height: 80)
.clipShape(Circle())
Text(authManager.user?.displayName ?? "")
.font(.system(.title, design: .rounded))
Text(authManager.user?.email ?? "")
.font(.subheadline)
.foregroundColor(.gray)
NavigationLink {
EditProfileView()
} label: {
Text("Edit profile")
.frame(minWidth: 0, maxWidth: .infinity)
.font(.system(size: 18))
.padding(10)
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(25)
}
.padding(.top, 5)
}
.frame(maxWidth: .infinity, alignment: .center)
}
I want only the button to be clickable. How can I fix this?
Thanks!
Link to issue: https://imgur.com/a/iO9aNSM
The SwiftUI previews have been working fine in Xcode 16.0 beta, but ever since I added Firebase into my app, I've been getting error with previews.
CrashReportError: IshaanCord crashed
IshaanCord crashed. Check ~/Library/Logs/DiagnosticReports for crash logs from your application.
Process: IshaanCord[5651]
Date/Time: 2024-07-04 19:29:51 +0000
Log File: <none>
"Cannot preview in this file"
Does anyone know how to fix this? Thank you.
Hi, I can't get onScrollPhaseChange to fire when using a List. It works as expected when using a ScollView and LazyVStack.
Interestingly, onScrollGeometryChange gets called as expected for both List and ScrollView.
Has anyone successfully used onScrollPhaseChange with a List?
brand new newbie developer to xcode. so im doing an api call and getting back data from a mysql database. in the xcode preview window im getting data, but i cant figure out how to tie it to the screen when going into the simulator. i have screen 1 that i want to click a button to go to screen 2 that displays the data. screen one (home screen) comes up okay. cant quite figure out what im doing wrong here. im thinking its either a class issue or something to do with view or something. not sure. ive tried looking at so many different videos and i cant seem to find my answer. Any help would be appreciated. thank you
View Controller:
import UIKit
//import SwiftUI
let URL_TOURNAMENT_FETCH = "https://www.thesoftball.com/t2g_mobile_app/mobile_api.php"
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func onEmailButtonPressed(_ sender: Any)
{
UIApplication.shared.open(URL(string: "mailto:[email]")! as URL, options: [:],completionHandler: nil)
}
/*
@IBAction func FetchTournButton(_ sender: Any) {
UIApplication.shared.open(URL(string: "https://www.thesoftball.com/t2g_mobile_app/mobile_api.php")! as URL, options: [:],completionHandler: nil)
}
*/
@IBAction func ViewTournamentButton(_ sender: Any)
{
// the following is a popup
let alertController = UIAlertController(title: "Welcome to My First App", message: "Hello World", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
present(alertController, animated: true, completion: nil)
}
@IBAction func account_button_pressed(_ sender: Any)
{
UIApplication.shared.open(URL(string: "https://www.thesoftball.com")! as URL, options: [:],completionHandler: nil)
}
/*
struct viewDidLoadModifier: viewDidLoadModifier
{
@State private var didLoad = false
private let action: (() -> void)?
init(perform action)
{
}
}
*/
}
ContentView (preview works in this)
import SwiftUI
struct ContentView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
NavigationView{
List{
ForEach(viewModel.courses,id: \.self) { tournament in
HStack {
Image("")
.frame(width: 5, height: 120)
.background(Color.orange)
VStack {
Text(tournament.name).bold()
Text(tournament.dates)
Text(tournament.datee)
Text(tournament.location)
// Text(course.location)
// Text(course.message)
// .bold()
}
}
.padding(0)
}
}
.navigationTitle("Tournaments")
// .onAppear { viewModel.fetch()}
.onAppear(perform: viewModel.fetch)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
So I am banging my head, I realized my stand along Watch App had a STUPID long name of "App Name - WatchKit App" so I went into my Target and changed the Display Name to "App Name" removing WatchKit App. Well now my app won't validate when uploading to the Appstore. I get the message - Invalid Info.plist key. The key
WKExtensionDelegateClassName in bundle App Name.app/Watch/App Name WatchKit App.app is invalid.
My Info.plist has the value of
<key>WKExtensionDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).ExtensionDelegate</string>
I have confirmed that I have @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate in my @main for the SwiftUI App. And when I print a few values in my app launch I get the following confirmations:
Super Init - ExtensionDelegate
Contentview
applicationDidFinishLaunching for watchOS
Super Init - ExtensionDelegate
Optional(My_App_Extension.Setup)
Optional(My_App_Extension.Statistics)
Optional(My_App_Extension.Other)
applicationDidBecomeActive for watchOS
update complication
I create three classes at launch and print this in the log with print(ExtensionDelegate.shared.Setup as Any) , etc. The other lines are just confirming where I am at app startup.
This is a WatchOS8 application and I am running Xcode version Version 13.1 (13A1030d).
Hey,
I have a setup in my app that I am currently building, that uses @Observable router objects that hold the app's entire navigation state, so that I can easily set it globally and let SwiftUI show the appropriate views accordingly. Each view gets passed in such a router object and there is a global "app" router that the app's root view can access as an entry point:
@Observable @MainActor
final class AppRouter {
static let shared = AppRouter() // Entry point used by the app's root view
var isShowingSheet = false // Navigation state
let sheetRouter = SheetRouter() // Router that's passed to the sheet view. This router could contain other routers for sheets it will show, and so on
}
@Observable @MainActor
final class SheetRouter { // Example of a "nested" router for a sheet view
var path = NavigationPath()
var isShowingOtherSheet = false
func reset() {
path = .init()
isShowingOtherSheet = false
}
}
To open a sheet, I have a button like this:
@Bindable var appRouter = AppRouter.shared
// ...
Button("Present") {
appRouter.sheetRouter.reset() // Reset sheet router
appRouter.isShowingSheet = true // show sheet
}
This seems to work perfectly fine. However, this produces tons of "error" logs in the console, whenever I open the sheet for a second time:
Mutating observable property \SheetRouter.path after view is torn down has no effect.
Mutating observable property \SheetRouter.path after view is torn down has no effect.
Mutating observable property \SheetRouter.path after view is torn down has no effect.
Mutating observable property \SheetRouter.path after view is torn down has no effect.
Mutating observable property \SheetRouter.isShowingOtherSheet after view is torn down has no effect.
These errors appear when calling the reset() of the sheet view's router before opening the sheet. That method simply resets all navigation states in a router back to their defaults. It's as if the sheetRouter is still connected to the dismissed view from the previous sheet, causing a mutation to trigger these error logs.
Am I misusing SwiftUI here or is that a bug? It's also worth mentioning that these error logs do not appear on iOS 17. Only on iOS 18. So it might be a bug but I just want to make sure my usage of these router objects is okay and not a misuse of the SwiftUI API that the runtime previously simply did not catch/notice. Then I'd have to rewrite my entire navigation logic.
I do have an example project to demonstrate the issue. You can find it here: https://github.com/SwiftedMind/PresentationBugDemo.
I have also filed a feedback for this: FB14162780
STEPS TO REPRODUCE
Open the example project.
Open the sheet in the ContentView twice by tapping "Present"
Close that sheet
Open it again.
Then the console will show these error logs from above.
I'd appreciate any help with this.
Cheers
I am making application where I use navigation link to navigate from bottom menu to other views, and there is a problem when I change view a few times because views start stacking and when I set navigationBarBackButtonHidden(false) I can see on left side a lot of back button. This generate big problem because after changing views I got warning Abnormal number of gesture recognizer dependencies: 100. System performance may be affected. Please investigate reducing gesture recognizers and/or their dependencies. And after some more changes everything from screen is pushed down back button. Is there any solution to close previous view from we came?
There is code:
//
// BottomMenu.swift
// SpaceManager
//
// Created by Kuba Kromomołowski on 04/05/2024.
//
import SwiftUI
import Firebase
import FirebaseAuth
struct BottomMenu: View {
@StateObject var logManager = MainViewModel()
@StateObject var mvm = MenuViewModel()
@State var condition1: Bool = true
@State var condition2: Bool = false
@State var condition3: Bool = false
// @StateObject private var cameraViewModel = CameraViewModel()
var body: some View {
HStack{
Group{
//.navigationBarBackButtonHidden(true)
Spacer()
BtnMenu(btnText: "Dodaj",
btnIcon: "plus.app.fill",
destinationView:AnyView(LoggedMainView()),
isActive: condition1
)
Spacer()
BtnMenu(btnText: "Szukaj",
btnIcon: "magnifyingglass",
destinationView:AnyView(SearchView()),
isActive: condition2
)
Spacer()
BtnMenu(btnText: "Profil",
btnIcon: "person.crop.circle.fill",
destinationView:AnyView(ProfileView()),
isActive: condition3
)
Spacer()
}.padding(.bottom, 30)
.font(.system(size: 20))
}
}
}
#Preview {
BottomMenu()
}
//
// BtnMenu.swift
// SpaceManager
//
// Created by Kuba Kromomołowski on 04/05/2024.
//
import SwiftUI
struct BtnMenu: View {
var btnText: String
var btnIcon: String
var destinationView: AnyView
@State var isActive: Bool = true
var body: some View {
NavigationLink{
destinationView
} label: {
ZStack {
Text("\(Image(systemName: btnIcon)) \(btnText)")
}
}.disabled(isActive)
}
}
I am trying to configure scenes to capture a redirect URL after a successful login attempt. I am using OAuth code flow. This is the code I have so far:
ios_app.swift
import SwiftUI
@main
struct ios_appApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
let persistenceController = PersistenceController.shared
@StateObject private var authState = AuthState()
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.environmentObject(authState)
}
}
}
AppDelegate.swift
import UIKit
import AWSMobileClient
import GoogleSignIn
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
print("AppDelegate: didFinishLaunchingWithOptions")
AWSMobileClient.default().initialize { (userState, error) in
if let userState = userState {
print("UserState: \(userState)")
} else if let error = error {
print("Error initializing AWSMobileClient: \(error.localizedDescription)")
}
}
GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
if let error = error {
print("Error restoring previous Google Sign-In: \(error.localizedDescription)")
}
}
return true
}
}
SceneDelegate.swift
import UIKit
import SwiftUI
import GoogleSignIn
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
print("SceneDelegate: scene willConnectTo")
guard let windowScene = (scene as? UIWindowScene) else {
print("SceneDelegate: Invalid windowScene")
return
}
let window = UIWindow(windowScene: windowScene)
let contentView = ContentView().environmentObject(AuthState())
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
print("SceneDelegate: window initialized and visible")
}
func sceneDidDisconnect(_ scene: UIScene) {
print("SceneDelegate: sceneDidDisconnect")
}
func sceneDidBecomeActive(_ scene: UIScene) {
print("SceneDelegate: sceneDidBecomeActive")
}
func sceneWillResignActive(_ scene: UIScene) {
print("SceneDelegate: sceneWillResignActive")
}
func sceneWillEnterForeground(_ scene: UIScene) {
print("SceneDelegate: sceneWillEnterForeground")
}
func sceneDidEnterBackground(_ scene: UIScene) {
print("SceneDelegate: sceneDidEnterBackground")
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else {
print("SceneDelegate: No URL found in URLContexts")
return
}
print("SceneDelegate: openURLContexts with URL: \(url)")
if GIDSignIn.sharedInstance.handle(url) {
print("SceneDelegate: Google Sign-In handled URL")
return
}
if url.scheme == "myurlscheme" || (url.scheme == "https" && url.host == "mydomain.com" && url.path == "/mobile-auth-callback") {
print("SceneDelegate: Handling auth response for URL: \(url)")
AuthService.shared.handleOAuthCallback(url: url)
} else {
print("SceneDelegate: URL scheme not handled: \(url.scheme ?? "No scheme")")
}
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
print("SceneDelegate: continue userActivity")
if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
if let url = userActivity.webpageURL {
handleUniversalLink(url: url)
}
}
}
private func handleUniversalLink(url: URL) {
print("SceneDelegate: Handling universal link: \(url)")
if url.path.contains("/mobile-auth-callback") {
let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems
let code = queryItems?.first(where: { $0.name == "code" })?.value
if let code = code {
print("SceneDelegate: Received code: \(code)")
AuthService.shared.exchangeCodeForToken(code: code)
} else {
print("SceneDelegate: No code found, handling email/password callback")
AuthService.shared.handleEmailPasswordCallback(url: url)
}
}
}
}
Also introduced this configuration in Info.plist:
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<true/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>ios-app.SceneDelegate</string>
</dict>
</array>
</dict>
</dict>
...Other parameters
</dict>
</plist>
I am using the simulator to launch my app and can see AppDelegate related logs but I am not seeing any SceneDelegate logs (I suppose because it is not being initialized nor called).
I have tried restarting the computer/Xcode, clean and rebuild the application but none of the things I tested work.
Is there any part of my code wrong? Any other idea here?
In the AudioServicesPlaySystemSound function of AudioToolbox, you can enter the corresponding SystemSoundID to play some sound effects that come with the system. However, I can't be sure what sound effect each number corresponds to, so I want to know all the sound effects in visionOS and its corresponding SystemSoundID.
In vision OS, the tab bar of TabView is outside the window by default.
If I switch a page without TabView to a page that needs TabView in my program, the tab bar will suddenly appear on the left side of the screen without any animation. I hope it has an animation when it appears (such as easeIn, move). I tried it in Tab. Other animation-related modifiers such as animation are added under View, but there is no animation in the tab bar. Only the view in the tab has an animation effect, but this is not what I want. What I want is that the tab bar outside the window can have animation. What should I do?
Hi I'm new to Swiftui.
I want to show a sheet and pass a var to it.
In the case below when I tap on a list view it will popup then disappear. But subsequent taps will work as intended.
Main view:
struct ContentView: View {
@State private var selectedMonth = 1
@State private var selectedYear = "2024"
let months = [1,2,3,4,5,6,7,8,9,10,11,12]
@State private var isShowing = false
var body: some View {
List {
ForEach (months, id: \.self) { month in
HStack {
ViewList(month: month, year: selectedYear)
}
.onTapGesture {
isShowing = true
selectedMonth = month
}
.sheet(isPresented: $isShowing){
PopupView(month: selectedMonth, year: selectedYear)
.presentationDetents([.large])
}
}
}
.listRowSpacing(2)
.listStyle(.grouped)
}
}
ViewList:
struct ViewList: View {
var month: Int
var year: String
@State private var selectedMonthText = "Jan"
var body: some View {
VStack (alignment: .leading) {
Text(selectedMonthText + " / " + year)
.font(.headline)
}
.onAppear {
switch month {
case 01:
selectedMonthText = "Jan"
case 02:
selectedMonthText = "Feb"
case 03:
selectedMonthText = "Mar"
case 04:
selectedMonthText = "Apr"
case 05:
selectedMonthText = "May"
case 06:
selectedMonthText = "Jun"
case 07:
selectedMonthText = "Jul"
case 08:
selectedMonthText = "Aug"
case 09:
selectedMonthText = "Sep"
case 10:
selectedMonthText = "Oct"
case 11:
selectedMonthText = "Nov"
case 12:
selectedMonthText = "Dec"
default:
selectedMonthText = "All"
}
}
}
}
Then my popup:
struct PopupView: View {
@Environment(\.dismiss) var dismiss
var month: Int
var year: String
@State private var selectedMonthText = "Jan"
@State private var imageText = "plus"
@State private var items = ["Cat", "Dog", "Bird", "Snake"]
var body: some View {
Button("Dismiss"){
dismiss()
}
Text(selectedMonthText + " / " + year)
List {
ForEach(items, id: \.self) {item in
HStack {
Text(item)
Text("Fed on: ")
Text(selectedMonthText)
}
}
}
.listRowSpacing(0)
.listStyle(.inset)
.onAppear {
switch month {
case 01:
selectedMonthText = "Jan"
case 02:
selectedMonthText = "Feb"
case 03:
selectedMonthText = "Mar"
case 04:
selectedMonthText = "Apr"
case 05:
selectedMonthText = "May"
case 06:
selectedMonthText = "Jun"
case 07:
selectedMonthText = "Jul"
case 08:
selectedMonthText = "Aug"
case 09:
selectedMonthText = "Sep"
case 10:
selectedMonthText = "Oct"
case 11:
selectedMonthText = "Nov"
case 12:
selectedMonthText = "Dec"
default:
selectedMonthText = "All"
}
}
}
}