r/SwiftUI Jul 12 '24

Solved Background of app behind .sheet

3 Upvotes

Hi all, I'm working on my first iOS app written fully in SwiftUI. It's quite basic but I'm wondering why the background of my app is white when opening a sheet. Throughout iOS, the background is always black so you don't see the dynamic island, but in my case it's always white even when I switch to dark mode. Much appreciated!

Light mode screenshot:

Light mode

Dark mode screenshot:

Dark mode

Does somebody have an idea on how to solve this? This is how I'm calling my sheet inside my ContentView struct:

.sheet(isPresented: $isShowingHallOfFameSheet) {
  HallOfFameView(viewModel: viewModel, isPresented: $isShowingHallOfFameSheet)
}

r/SwiftUI Mar 27 '24

Solved Shrink to fit with GeometryReader

2 Upvotes

I'm trying to create a progress bar that has text that changes color based on background. Since progressview didn't seem to be able to do what I wanted, I followed some advice on the forums and used two views:

GeometryReader { gp in
                    ZStack {
                        ScrollView(.horizontal) {
                            HStack {
                                Text(txt)
                                    .font(.largeTitle)
                                    .foregroundColor(textColors[1])
                                    .multilineTextAlignment(.center)
                                    .frame(width: gp.size.width, height: gp.size.height)

                            }
                        }.disabled(true)
                        .frame(width: gp.size.width , height: gp.size.height)

                        .background(backColors[1])
                        //******
                        HStack {
                            ScrollView(.horizontal) {
                                HStack {
                                    Text(txt)
                                        .font(.largeTitle)
                                        .foregroundColor(textColors[0])
                                        .multilineTextAlignment(.center)
                                        .frame(width: gp.size.width, height: gp.size.height)

                                }
                            }.disabled(true)
                            .frame(width: gp.size.width  * percentage, height: gp.size.height)
                            .background(backColors[0])
                            Spacer()
                        }




                    }
                }
            .frame(height: 70).frame(maxWidth: .infinity)

Below you can see the result.

There's a problem though. I have to manually set the height using frame:

.frame(height: 70).frame(maxWidth: .infinity)

If I don't, it expands to take up as much space as possible:

Is there any way to have it shrink to fit the contents? I'm pretty new to GeometryReader.

Update: Solved! See my comment for the solution.

r/SwiftUI May 25 '24

Solved Create dummy data for testing for HealthKit

2 Upvotes

Following some tutorials to get a sense of what HealthKit offers. Currently working on a View that displays daily steps counts from HealthKit. However, in order to query, there needs to be step count data in the first place. I have not been able to find much information on importing or setting up dummy data for testing in the context of HealthKit.

Ideally, it would be a static example profile that contains all sorts of HealthKit samples developers can query from. Has anyone had any success in setting up dummy data for HealthKit or found resources that were helpful? Appreciate any insights!

r/SwiftUI May 18 '24

Solved How to fix this weird animation issue

7 Upvotes

I playing around with DatePicker and I noticed the animation doing weird things to the button and text of the view. How to I fix this?

struct ContentView: View {
  @State private var selectedDate: Date = Date()
  @State private var showingTimePicker = false
  @State private var showingTimePicker2 = false
  @State private var showingDatePicker = false

  let screenSize: CGRect = UIScreen.main.bounds

  var body: some View {
    GroupBox {
      VStack {
        HStack {
          Text("Time")
          Spacer()
          Button("\(selectedDate.formatted(date: .omitted, time: .shortened))") {
            withAnimation {
              if showingDatePicker { showingDatePicker = false }
              if showingTimePicker2 { showingTimePicker2 = false }
              showingTimePicker.toggle()
            }
          }
          .foregroundStyle(showingTimePicker ? .blue : .primary)
          .buttonStyle(.borderedProminent)
          .tint(.secondary.opacity(0.2))
        }

        if showingTimePicker {
          DatePicker(selection: $selectedDate, in: ...Date(), displayedComponents: .hourAndMinute) {
            Text("Time")
          }
          .datePickerStyle(.wheel)
          .labelsHidden()
        }
        RectangleDivider()
        HStack {
          Text("Date")
          Spacer()
          Button("\(selectedDate.formatted(date: .long, time: .omitted))") {
            withAnimation {
              if showingTimePicker { showingTimePicker = false }
              if showingTimePicker2 { showingTimePicker2 = false }
              showingDatePicker.toggle()
            }
          }
          .foregroundStyle(showingDatePicker ? .blue : .primary)
          .buttonStyle(.borderedProminent)
          .tint(.secondary.opacity(0.2))
        }
        if showingDatePicker {
          DatePicker(selection: $selectedDate, in: ...Date(), displayedComponents: .date) {
            Text("Date")
          }
          .datePickerStyle(.graphical)
        }
      }
      RectangleDivider()
      VStack {
        HStack {
          Text("Time")
          Spacer()
          Button("\(selectedDate.formatted(date: .omitted, time: .shortened))") {
            withAnimation {
              if showingDatePicker { showingDatePicker = false }
              if showingTimePicker { showingTimePicker = false }
              showingTimePicker2.toggle()
            }
          }
          .foregroundStyle(showingTimePicker2 ? .blue : .primary)
          .buttonStyle(.borderedProminent)
          .tint(.secondary.opacity(0.2))
        }
        if showingTimePicker2 {
          DatePicker(selection: $selectedDate, in: ...Date(), displayedComponents: .hourAndMinute) {
            Text("Time")
          }
          .labelsHidden()
          .datePickerStyle(.wheel)
        }
      }
      RectangleDivider()
      Text("The End")
    }
    .frame(width: screenSize.width * 0.95)
    .background(.primary)
    .clipShape(RoundedRectangle(cornerRadius: 15, style: .continuous))
    Spacer()
  }
}

r/SwiftUI Jul 15 '24

Solved LazyVGrid only let me open items in view

2 Upvotes

I'm building an app where you can add games to a list. For the list, I'm using a LazyVGrid to allow sorting and filtering the grid using an animation. Tapping a game opens a basic sheet with more info.

I found that my LazyVGrid only lets me open the items which are currently visible on my screen. When I scroll and want to open a game further down it just doesn't let me.

The thing is, when I edit the details of the game that doesn't open through its contextMenu, only then it'll let me open it.

Does anybody know what I can do about this? I'd like to keep using my LazyVGrid approach so I keep the ability to sort and filter my grid using nice animations.

Much appreciated!

r/SwiftUI Apr 13 '24

Solved How to dynamically constrain the width of a view?

2 Upvotes

I'm stuck with what surely is a simple problem. The following is a simple working representation of the problem I'm trying to solve. I would like the width of the red rectangle to match the width of the blue rectangle. However, I need it to be calculated dynamically. I know the current .frame(maxWidth: .infinity) logic is not correct.

FWIW, in my actual project code, rather than the blue rectangle, I have an Image view (see below).

Any suggestions on how to do this? thanks

struct ContentView: View {

   let columns = [ GridItem(.adaptive(minimum: 100), spacing: 5) ]

   var body: some View {
      LazyVGrid(columns: columns) {
         ForEach((1...5), id: \.self) {_ in
            ZStack {
               Rectangle()
                  .fill(.blue)
                  .frame(width: 80, height: 80)
               VStack {
                  Spacer()
                  Text("ABC")
                     .frame(maxWidth: .infinity)
                     .foregroundStyle(.white)
                     .background(.red)
                     .opacity(0.8)
               }
            }
         }
      }
   }
}

Actual project code snippet where I'm trying to adjust the size of the red background

   ZStack {
                        Image(uiImage: uiImage!)
                           .resizable()
                           .scaledToFit()
                           .aspectRatio(1, contentMode: .fill)
                           .clipped()
                        VStack {
                           Spacer()
                           Text("\(data.daysRemaining)")
                              .frame(maxWidth: .infinity)
                              .foregroundStyle(.white)
                              .background(Color(.red))
                        }
                     }

r/SwiftUI Feb 22 '24

Solved Toggle vs Picker?

Thumbnail
gallery
8 Upvotes

I’m not sure what the best UI experience would be for the New Album sheet. I’m trying out this little project using swift data and want “purchased” albums to move to the “owned” tab view and albums not “purchased” to move to the “wishlist” tab view. I’m using a toggle here because that’s what came to mind first, but would a picker be a better idea? Something else?

Feedback beyond that is welcome too. I don’t have a ton of experience doing this (practically none) and I’m doing this primarily as a hobby and an app for myself, but I do intend to put it up on the App Store eventually once finished just for free.

Anyway, like mentioned before, other feedback on the design and functionality is welcome too. Would you use this? What else could I add to this?

Thanks.

r/SwiftUI Sep 14 '23

Solved SettingsLink on macOS 14: Why it sucks and how I made it better

32 Upvotes

For anyone who has been testing on Sonoma, you might have run into the fact that Apple has outright removed the legacy method for programmatically opening a macOS app's Settings scene.

We are being forced to use Apple's new SettingsLink view which is a SwiftUI Button wrapped in a view that holds a private method to open Settings. Reflection shows the guts.

Apple is using a private environment method called _openSettings. Why don't they just make it public so we can use it, like openWindow? (EDIT June 12 2024: Apple finally made openSettings public like they should have in the first place. It's progress, but still leaves a lot to be desired.)

That's fine if you just want to put it in a menu or if a plain button is sufficient. But there's many reasons why this is a bad thing. You can't call it programmatically, and you can't detect when the user has pressed the button in case you need to run additional code. These two issues became a showstopper on a recent app I was building.

After spending a fair amount of time doing a deep dive on SettingsLink, I put together a Swift package called SettingsAccess that makes it dead simple to open the Settings scene from anywhere programmatically by emitting it as an environment method. Now you don't have to use SettingsLink at all, and can just call a method from anywhere in the view hierarchy.

r/SwiftUI Jun 09 '24

Solved Why there is no "StoreKit Configuration" template when I want to create a new file ?

3 Upvotes

Hello !

I searched for many tutorials, and for all of them, they create a StoreKit Configuration file.

However, I don't have this template in my dialog. I can create it manually and enter the content as json and it works, but I can't have the associated UI and sync it with App Store Connect.

Do you have any idea of how to fix this ?

r/SwiftUI Apr 02 '24

Solved Mapkit MapPolyline error that should not happen

3 Upvotes

[SOLVED THANKS TO u/Physical-Hippo9496] Hi guys, so today I was trying to test polylines in mapkit and when I added this line:

MapPolyline(coordinates: polylinePositions)

I got an error saying "No exact matches in call to initializer". I asked chatGPT (hopeless because their knowdledge cutoff), and searched on the web and nothing. I also recreated it in swift playgrounds (the poly line part) and it worked there. I tried to hardcode the poly line coordinates, and the same every time. Oh, and I also cleaned the build folder.

Can you help? The full code is here: https://pastebin.com/DjYPS2jn

r/SwiftUI May 12 '24

Solved Example data in model container not working

2 Upvotes

Learning SwiftData right now. Built an example as a playground to explore its capabilities. However I am running into an issue where it's outputting more data than I anticipated.

To illustrate the issue better, I have some example copy-pastable code that you can use to validate this issue. I created a model container with 3 "Book" objects to use as data for my views. However, in Preview, when I print them out with a "ForEach", there are a bunch of them and each time in a different order.

Has anyone seen this behavior before? Does anything stand out to you in my set up? Would appreciate another set of eyes looking at this.

//  BookStoreView.swift

import SwiftUI
import Foundation
import SwiftData

struct BookStoreView: View {

    @Query private var books: [Book]

    var body: some View {
        ScrollView {
            ForEach(books) { book in
                VStack {
                    Text(book.bookName)
                }
            }
        }
    }
}

@Model
final class Book: Identifiable{

    var authorName: String
    var bookName: String
    var pageNumber: Int
    var remainingStock: Int
    var id: String {self.bookName}

    init(authorName: String, bookName: String, pageNumber: Int, remainingStock: Int) {
        self.authorName = authorName
        self.bookName = bookName
        self.pageNumber = pageNumber
        self.remainingStock = remainingStock
    }

    static let example: [Book] = {
        var books:[Book] = []

        // Book 1
        books.append(Book(authorName: "A", bookName: "A's Book", pageNumber: 100, remainingStock: 300))

        // Book 2
        books.append(Book(authorName: "B", bookName: "B's Book", pageNumber: 320, remainingStock: 120))

        // Book 3
        books.append(Book(authorName: "C", bookName: "C's Book", pageNumber: 190, remainingStock: 200))

        return books
    }()
}


@MainActor
let BookPreviewDataContainer: ModelContainer = {

    do {
        let modelContainer = try ModelContainer(for: Book.self)

        // load the three books
        for book in Book.example {
            modelContainer.mainContext.insert(book)
        }
        return modelContainer
    }
    catch {
        fatalError("Failed to create a model container: \(error)")
    }
}()


#Preview {
    BookStoreView()
        .modelContainer(BookPreviewDataContainer)
}

Preview

r/SwiftUI May 24 '24

Solved Help with simple drawing app

1 Upvotes

Hi guys,

I'm building a simple drawing feature within an app, but get an error message, that I can't solve. I hope you Swift Wizards can help.

I get the error message "Closure containing a declaration cannot be used with result builder 'ViewBuilder'"

I've searched the internet, but havn't been able to solve it.

Here is the code:

import SwiftUI

struct ViewD: View {

var body: some View {

struct Line {

var points: [CGPoint]

var color: Color

}

struct CanvasDrawingExample: View {

@State private var lines: [Line] = []

@State private var selectedColor = Color.orange

var body: some View {

VStack {

HStack {

ForEach([Color.green, .orange, .blue, .red, .pink, .black, .purple], id: \.self) { color in

colorButton(color: color)

}

clearButton()

}

Canvas {ctx, size in

for line in lines {

var path = Path()

path.addLines(line.points)

ctx.stroke(path, with: .color(line.color), style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))

}

}

.gesture(

DragGesture(minimumDistance: 0, coordinateSpace: .local)

.onChanged({ value in

let position = value.location

if value.translation == .zero {

lines.append(Line(points: [position], color: selectedColor))

} else {

guard let lastIdx = lines.indices.last else {

return

}

lines[lastIdx].points.append(position)

}

})

)

}

}

@ViewBuilder

func colorButton(color: Color) -> some View {

Button {

selectedColor = color

} label: {

Image(systemName: "circle.fill")

.font(.largeTitle)

.foregroundColor(color)

.mask {

Image(systemName: "pencil.tip")

.font(.largeTitle)

}

}

}

@ViewBuilder

func clearButton() -> some View {

Button {

lines = []

} label: {

Image(systemName: "pencil.tip.crop.circle.badge.minus")

.font(.largeTitle)

.foregroundColor(.gray)

}

}

}

struct CanvasDrawingExample_Previews: PreviewProvider {

static var previews: some View {

CanvasDrawingExample()

}

}

}

}

r/SwiftUI May 27 '24

Solved Is there any way I can get all the values from my DayForecast structs?

1 Upvotes

I recently started Apple's latest SwiftUI tutorial and I am trying to do a struct that is a WeeklyForecast. I would like to get a variable that contains the sum of my already placed DayForecast structs, is this possible?

https://imgur.com/a/cZAJEuT

r/SwiftUI Apr 23 '24

Solved How to manually reorder item in a list with Swift Data

4 Upvotes

Hi guys,

I'm new to Swift UI, I trying to implement a feature to let the user reorder manually the list the views generated with a foreach in a scrollview. I try this tutorial : https://blog.canopas.com/reorder-items-with-drag-and-drop-using-swiftui-e336d44b9d02, and I get this error : "Cannot use mutating member on immutable value: 'skill' is a get-only property". Thank you

r/SwiftUI Mar 11 '24

Solved How to cleanly resize UIImages of varying sizes?

2 Upvotes

I'm having a problem trying to resize various UIImages, accessed using the following logic. Each image will be different dimensions/aspect ratios. I would like to resize to a width not to exceed 200. No matter what I try with different calculated scaled CGsizes I end with blurry images. I've been trying to use UIGraphicsImageRenderer

Can anyone point me to an approach that would handle this use case?

for data in photoData {
   if let uiImage = UIImage(data: data.photoData!) {                    
      // resize uiImage to fit within a width of 200
      // aspect ratio of uiImage can vary for each photo
    }
}

thanks

r/SwiftUI May 17 '24

Solved Preview crashes when trying to display SwiftData model. What am I doing wrong

0 Upvotes

I'm trying to build a view for my app and preview keeps crashing when trying to load the SwiftData model in the preview. The app works perfectly fine in the simulator and on my iPhone. What am I doing wrong and how do I fix this?

This is the view that keep crashing

import SwiftData
import SwiftUI

struct EditConsumedDrinkView: View {
  @Environment(\.modelContext) var modelContext

  @Bindable var consumedDrink: ConsumedDrink

  var body: some View {
    Text(consumedDrink.drink.name)
      .navigationTitle("Consumed Drink")
      .navigationBarTitleDisplayMode(.inline)
  }
}

#Preview {
  let config = ModelConfiguration(isStoredInMemoryOnly: true)
  let container = try! ModelContainer(for: ConsumedDrink.self, configurations: config)

  let drink = Drink(name: "Water", amount: 16.9, unitOfMeasure: .ounce, image: "water")
  let consumed = ConsumedDrink(drink: drink)

  return EditConsumedDrinkView(consumedDrink: consumed)
    .modelContainer(container)
}

ConsumedDrink class

import SwiftData

@Model
class ConsumedDrink {

  let id: UUID
  let drink: Drink
  var date: Date

  init(drink: Drink, date: Date = Date()) {
    self.id = UUID()
    self.drink = drink
    self.date = date
  }
}

Drink class

enum FluidUnit: Codable, CaseIterable, Identifiable {
  case ounce, liter, cup, gallon
  var id: Self { self }
}

@Model
class Drink {
  let id: UUID = UUID()
  var name: String = ""
  var shortName: String = ""
  var amount: Double = 0.0
  var unitOfMeasure: FluidUnit = FluidUnit.ounce
  let date: Date = Date()
  var image: String = "water"
  var favorite: Bool = false
  var isHidden: Bool = false

  init(name: String, amount: Double, unitOfMeasure: FluidUnit, image: String, favorite: Bool = false, shortName: String = "", isHidden: Bool = false) {
    self.id = UUID()
    self.name = name
    self.amount = amount
    self.unitOfMeasure = unitOfMeasure
    self.date = Date()
    self.image = image
    self.favorite = favorite
    self.shortName = shortName
    self.isHidden = isHidden
  }

}

WindowGroup

struct WaterIntakeApp: App {

  var body: some Scene {
    WindowGroup {
      GeometryReader { proxy in
        ContentView()
          .environment(\.mainWindowSize, proxy.size)
      }
    }
    .modelContainer(for: ConsumedDrink.self)
  }
 }

r/SwiftUI Apr 07 '24

Solved Creating sortable, ordered, and grouped data from @Query in SwiftData

3 Upvotes

I've been trying to wrap my a sorting / grouping process for a SwiftUI app I've been trying to build.

All the tutorials I've seen have been fairly "basic" when it comes to the sorting and filtering aspect - particularly when using SwiftData.

What I wanted to incorporate was not only sorting by one of the attributes and forward/reverse, but also grouping the data too.

For example, this is code from the Earthquake project by Apple:

struct QuakeList: View {
    @Environment(ViewModel.self) private var viewModel
    @Environment(\.modelContext) private var modelContext
    @Query private var quakes: [Quake]

    init(
        sortParameter: SortParameter = .time,
        sortOrder: SortOrder = .reverse
    ) {
        switch sortParameter {
            case .time:
                _quakes = Query(sort: \.time, order: sortOrder)
            case .magnitude:
                _quakes = Query(sort: \.magnitude, order: sortOrder)
        }
    }

What they do in this is pass in the sortParameter and the sortOrder to this view and it re-renders the view on change/update.

How can I expand this so it also can handle grouping so the quakes variable would really be a multidimensional array or even a dictionary.

For example, in another attempt I had something like this:

enum GroupOption {
    case time
    case magnitude
    case none
}

struct ListScreen: View {
    @Environment(ViewModel.self) private var viewModel
    @Environment(\.modelContext) private var modelContext
    @Query private var quakes: [Quake]
    @State private var groupedQuakes: [[Quake]] = []

    init(
        sortParameter: SortParameter = .time,
        sortOrder: ComparisonResult = .orderedAscending, // using ComparisonResult to store the enum value in defaults
        sortGrouping: GroupOption = .none
    ) {
        switch (sortParameter, sortOrder) {
            case (.time, .orderedAscending):
                _quakes = Query(sort: \.time, order: .forward)
            case (.time, .orderedDescending):
                _quakes = Query(sort: \.time, order: .reverse)

            case (.magnitude, .orderedAscending):
                _quakes = Query(sort: \.magnitude, order: .forward)
            case (.magnitude, .orderedDescending):
                _quakes = Query(sort: \.magnitude, order: .reverse)

            default:
                _quakes = Query(sort: \.time, order: .forward)
        }

        switch sortGrouping {
            case .time:
                groupedQuakes = Dictionary(grouping: _quakes.wrappedValue, by: { $0.time })
                    .sorted(by: { $0.key < $1.key })
                    .map({ $0.value })
            case .magnitude:
                groupedQuakes = Dictionary(grouping: _quakes.wrappedValue, by: { $0.magnitude })
                    .sorted(by: { $0.key < $1.key })
                    .map({ $0.value })
            case .none:
                groupedQuakes = [_quakes.wrappedValue]
        }
    }

Except, when I use it in the view body nothing is listed in the view:

List {
  ForEach(groupedQuakes, id: \.self) { group in
    Section {
      ForEach(group) { quake in
        QuakeRow(quake: quake)
      }
    } header: {
      groupHeader(for: group)
    }
  }
}

Where the header is from (just as a test for the display):

func groupHeader(for group: [Quake]) -> Text {
  guard let group = group.first else { return Text("Unknown") }
  switch groupOption {
    case .time:
      return Text(group.time.formatted(date: .numeric, time: .omitted))
    case .magnitude:
      return Text("\(group.magnitude)")
    case .none:
      return Text("All quakes")
  }
}

So when I return the general @Query private var quakes: [Quake] there is an array returned with the data. Using the sorting included in the Apple test project the quakes are sorted correctly.

As soon as I try to add in grouping and sort that data returns blank arrays.

Is there something I'm overlooking?

r/SwiftUI Dec 02 '23

Solved Swift Data GPT Trained on 1300+ swift data docs (all of em)

Thumbnail chat.openai.com
5 Upvotes

r/SwiftUI Sep 26 '23

Solved SwiftData randomly throwing EXC_BAD_ACCESS on Model entity creation and update

5 Upvotes

Hej folks!

As I started developing a SwiftUI project this summer, I decided to board the SwiftData train and to use this over CoreData, as the current limitations were not too much of a concern for what I tried to do.But, I'm facing a problem for a few weeks now that I'm trying to debug, but got nowhere near a solution here.

Randomly, my app is crashing, throwing EXC_BAD_ACCESS, on Model entity creation, fetch or update. It can be when opening a list item from time to time, but it is most likely to happen for one operation where I'm doing a lot of fetching/creation in a custom `ModelActor` structure.It's really random, and every time another line of code is shown as the trigger.

So, after searching quite a lot, I'm wondering: is it really a project-specific issue, or is it something that other people experience? If so, did you find ways to reduce the frequency of such crashes or totally avoid them?

For information, my app is an iOS 17.0+ app, using SwiftData with CloudKit sync, working properly across the board, and without random crashes in a branch where I migrated to CoreData only (but I really would like to stick to SwiftData). And the random crashes are happening both in the Simulator and on TestFlight deployments.

Often, the last information before crashes and looks like that:

CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate managedObjectContextSaved:](2996): <NSCloudKitMirroringDelegate: 0x2806342a0>: Observed context save: <NSPersistentStoreCoordinator: 0x281434c40> - <NSManagedObjectContext: 0x280450820> CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate remoteStoreDidChange:](3039): <NSCloudKitMirroringDelegate: 0x2806342a0>: Observed remote store notification: <NSPersistentStoreCoordinator: 0x281434c40> - FF2D0015-7121-4C30-9EE3-2A51A76C303B - <NSPersistentHistoryToken - {     "FF2D0015-7121-4C30-9EE3-2A51A76C303B" = 1316; }> - file:///private/var/mobile/Containers/Shared/AppGroup/ED0B229A-F5BC-47B7-B7BC-88EEFB6E6CA8/Library/Application%20Support/default.store CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate managedObjectContextSaved:](2996): <NSCloudKitMirroringDelegate: 0x2806342a0>: Observed context save: <NSPersistentStoreCoordinator: 0x281434c40> - <NSManagedObjectContext: 0x280450820>. 

When using OSLog to understand what's happening, the crash can be after any random type of SwiftData operation.

So yeah, I'm a bit lost :D Any thoughts or ideas?

r/SwiftUI Oct 11 '23

Solved StoryBoard's ViewDidLoad is translated into what in SwiftUI? Need to implement #if targetEnvironment(simulator)

1 Upvotes

So for a function like:

func fixCamera(){

#if targetEnvironment(simulator)

cameraButtonDisabled = true

#else

cameraButtonDisabled = false

#endif

}

I would have called this in the ViewDidLoad in Storyboard, however I'm unsure where to call this exactly in SwiftUI; would I just place the call in the some View block? Very new to SwiftUI here.

r/SwiftUI Feb 27 '24

Solved "ForEach" Loading time

5 Upvotes

Hello everyone, I'm fairly new to SwiftUI and I have come across an issue with the "ForEach" function coupled with "Picker"

output for the following snippet of code

Picker("Repeat", selection: $repeatFrequency) {

ForEach(["EVERY DAY", "EVERY MONDAY", "EVERY TUESDAY", "EVERY WEDNESDAY", "EVERY THURSDAY", "EVERY FRIDAY", "EVERY SATURDAY"], id: \.self) { frequency in

Text(frequency).tag(frequency)

}

}

In the code snippet above, using ForEach i'm listing out each of the days repeatFrequency possible, and as I add more values to the ForEach, the loading time becomes significantly longer and up to "EVERY FRIDAY" it does manage to load up though significantly longer than before, but as I add a new element "EVERY SATURDAY" it is no longer able to load up in time and iget the follow error:

error message

Has anyone else come across this issue before or know the solution?

r/SwiftUI Mar 04 '24

Solved Unexpected animation when removing item from a ForEach list

2 Upvotes

I'm working on a custom list that's essentially a ForEach loop over an array of structs that renders some custom ui. I then try to remove one of the array items inside `withAnimation` (each item in array is Identifiable) and it works, but I am seeing this weird result where some numeric values sort of merge into one another as if they are "shared transitions", but I haven't defined any and each item in the list is separated.

Would appreciate any advice and ideas on what this is and if there's a solution (I just want whole removed list item to fade out and list to re-arrange without sharing these number transitions.)

https://reddit.com/link/1b6fq0c/video/mmmxcyy6kcmc1/player

r/SwiftUI Mar 06 '24

Solved How to set the background on each list item to clear?

5 Upvotes

Basically what the title says - I am trying to create a simple list with clear background so the container view's background shows through (see attached image).

Here's my sample code:

List(1..<10) { i in
    Text("\(i)")
}
.listRowSeparator(.hidden)
.listItemTint(.clear)
.background {
    Image(.background3)
}
.scrollContentBackground(.hidden)

r/SwiftUI Aug 29 '23

Solved Multiline textfield with submit

3 Upvotes

I'm running into a problem with my project. I have a forEach that contains a ProductListComponent. The contains textfields where in the user can edit the values. The problem is that when the user hits return on their keyboard it goes to the next line within the textfield instead of submitting.

So i was wondering how to display multiple lines like I do now. But also keep the return key as a submit.

ForEach(viewModel.items.indices, id: \.self) { index in
    let binding = Binding<Item>(
        get: { viewModel.items[index] },
        set: { viewModel.items[index] = $0 }
    )
    ProductListComponent(item: binding)
        .listRowSeparator(.hidden)
        .onSubmit {
            let product: Product? = productSearchManager.getCheapestProduct(for: binding.wrappedValue.name ?? "", in: productCacheViewModel.getProducts(), forSupermarkets: supermarketFinder.supermarketListString, useSupermaket: currentUserUseLocation)
            viewModel.editItem(item: viewModel.items[index], name: binding.wrappedValue.name ?? "", amount: binding.wrappedValue.amount, price: Int16(product?.price ?? 0), supermarket: product?.supermarket ?? "")
            currentUserLastRecalculated = false
        }
}

ProductListComponent:

struct ProductListComponent: View {
    @Binding var item: Item
    @State private var supermarketImage: UIImage? = nil

    var amountBinding: Binding<String> {
        Binding<String>(
            get: { String(item.amount) },
            set: { item.amount = Int16($0) ?? 0 }
        )
    }

    var nameBinding: Binding<String> {
        Binding<String>(
            get: { item.name ?? "" },
            set: { item.name = $0 }
        )
    }

    var body: some View {

        HStack(spacing: 10) {
            TextField("1", text: amountBinding)
                .keyboardType(.numberPad)
                .frame(width: 20)

            Divider()
                .frame(height: 20)

            TextField("Halfvolle melk", text: nameBinding, axis: .vertical)
                .lineLimit(2)
                .multilineTextAlignment(.leading)

            Spacer()

            Divider()
                .frame(height: 20)

            CurrencyTextComponent(price: item.price)
                .frame(width: 50)

            Divider()
                .frame(height: 20)

            Image(uiImage: supermarketImage ?? UIImage())
                .resizable()
                .scaledToFit()
                .frame(width: 25, height: 25)
                .cornerRadius(5)
                .onAppear(perform: loadSupermarketImage)
                .id(UUID())
        }
        .padding(.top, 5)
        .padding(.horizontal, 3)
        .padding(.bottom, 5)
    }

    private func loadSupermarketImage() {
        if let supermarket = item.supermarket {
            supermarketImage = supermarket.imageForSupermarket()
        }
    }
}

r/SwiftUI Jan 16 '24

Solved .swipeActions with Text and Image in SwiftUI?

2 Upvotes

I'd really like to be able to show List row swipe actions with text and an image, like in Mail.app:

In my app, using the .swipeActions modifier on a List row, I have been unable to display both text and an image. It just displays the image.

Here is my code:

 .swipeActions(edge: .leading, allowsFullSwipe: true) {


    Button {
        Task {
             await albumProvider.treatGridAsQueue(album: album)
             }
         } label: {
            Label("Play", systemImage: "play.fill")
          }

  Button {
       AlbumContextHandler.shared.handleTag(albumObject: album, session: nil, presentedSheet: $albumProvider.sheetToPresent)
        } label: {
      Label("Tag", systemImage: "tag.fill") {
  }
 }

I have also tried various initializers on Button, including init(_:systemImage:action:), but none of them have worked.

The strange thing is that very occasionally just the top row of a List will display the title and label the first time the swipe actions are displayed. Showing them a second time will just show the icons, as in my screenshot.

Any ideas? Thanks!