I'm coming back to iOS development after years away and diving head-first into SwiftUI. It's a lot of fun, but I've hit a brick wall.
The scenario is I have a main view (which itself is a tabview, not important other than that it's not the top-level of the view hierarchy). This has subviews that rely on data coming back from a REST call to the cloud, but then some subviews need to turn around and make subsequent network calls to set up websockets for realtime updates.
In the main view's .onAppear, I fire off an async REST call, it returns JSON that gets parsed into a ModelView.
The ViewModel is declared in the top view like this:
class ViewModel: ObservableObject {
@Published var appData = CurrentREST() // Codables from JSON
@State var dataIsLoaded : Bool = false
func fetchData() async {
await _ = WebService().downloadData(fromURL: "current") { currentData in
DispatchQueue.main.async {
self.appData = currentData
self.dataIsLoaded = true
}
}
}
}
The main view declares the model view:
struct HomeTabView: View {
@ObservedObject var viewModel = ViewModel()
@Binding private var dataReceived: Bool
...
}
In the toplevel view, the REST call is triggered like this:
.onAppear {
if !viewModel.dataIsLoaded {
Task {
await viewModel.fetchData()
DispatchQueue.main.async {
self.dataReceived = true
}
}
}
}
The viewModel gets passed down to subviews so they can update themselves with the returned data. That part all works fine.
But it's the next step that break down. A subview needs to go back to the server and set up subscriptions to websockets, so it can do realtime updates from then on. It's this second step that is failing.
The dataReceived binding is set to true when the REST call has completed. The viewModel and dataReceived flags are passed down to the subviews:
SummaryView(viewModel: viewModel, dataIsLoaded: self.dataReceived)
What needs to happen next is inside the subview to call a function to wire up the next websocket steps. I've tried setting up:
struct SummaryView: View { @ObservedObject var viewModel: ViewModel @State var dataIsLoaded: Bool = false ... }.onChange(of: dataIsLoaded) { setupWebSocket() }
Problem is, the onChange never gets called.
I've tried various permutations of setting up a @State and a @Binding on the view model, and a separate @State on the main view. None of them get called and the subview's function that wires up the websockets never gets called.
The basic question is:
How do you trigger a cascading series of events through SwiftUI so external events (a network call) can cascade down to subviews and from there, their own series of events to do certain things.
I haven't gone deep into Combine yet, so if that's the solution, I'll go there. But I thought I'd ask and see if there was a simpler solution.
Any suggestions or pointers to best practices/code are most appreciated.
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Post
Replies
Boosts
Views
Activity
I have a background thread that is updating a swift data model Item using a ModelActor. The background thread runs processing an Item and updates the Item's status field. I notice that if I have a view like
struct ItemListView: View {
@Query private var items: [Items]
var body: some View {
VStack {
ForEach(items) { item in
ItemDetailView(item)
}
}
}
}
struct ItemDetailView: View {
var item: Item
var body: some View {
// expected: item.status automatically updates when the background thread updates the `Item`'s `status`.
Text(item.status)
// actual: This text never changes
}
}
Then background updates to the Item's status in SwiftData does not reflect in the ItemDetailView. However, if I inline ItemDetailView in ItemListView like this:
struct ItemListView: View {
@Query private var items: [Items]
var body: some View {
VStack {
ForEach(items) { item in
// Put the contents of ItemDetailView directly in ItemListView
Text(item.status)
// result: item.status correctly updates when the background thread updates the item.
}
}
}
}
Then the item's status text updates in the UI as expected. I suspect ItemDetailView does not properly update the UI because it just takes an Item as an input. ItemDetailView would need additional understanding of SwiftData, such as a ModelContext.
Is there a way I can use ItemDetailView to show the Item's status and have the UI show the status as updated in the background thread?
In case details about my background thread helps solve the problem, my thread is invoked from another view's controller like
@Observable
class ItemCreateController {
func queueProcessingTask() {
Task {
let itemActor = ItemActor(modelContainer: modelContainer)
await itemActor.setItem(item)
await itemActor.process()
}
}
}
@ModelActor
actor ItemActor {
var item: Item?
func setItem(_ item: Item) {
self.item = modelContext.model(for: item.id) as? Item
}
func process() async {
// task that runs processing on the Item and updates the Item's status as it goes.
}
Hi,
When I use 'listSectionSeparator' on hide the section separator on a List 'section', it works as expected on iOS, but doesn't have any effect on macOS. Is that a known issue? Are there any workarounds for this?
Here's a basic reproducible example:
import SwiftUI
struct TestItem: Identifiable, Hashable {
let id = UUID()
let itemValue: Int
var itemString: String {
get {
return "test \(itemValue)"
}
}
}
struct TestListSelection: View {
let testArray = [TestItem(itemValue: 1), TestItem(itemValue: 2), TestItem(itemValue: 3), TestItem(itemValue: 4)]
@State private var selectedItem: TestItem? = nil
var body: some View {
List (selection: $selectedItem) {
Section("Header") {
ForEach (testArray, id: \.self) { item in
Button {
print("main row tapped for \(item.itemValue)")
} label: {
HStack {
Text(item.itemString)
Spacer()
Button("Tap me") {
print("button tapped")
}
.buttonStyle(.borderless)
}
}
.buttonStyle(.plain)
}
}
.listSectionSeparator(.hidden) // has no effect on macOS
Section("2nd Header") {
ForEach (testArray, id: \.self) { item in
Text(item.itemString)
}
}
.listSectionSeparator(.hidden) // has no effect on macOS
}
.listStyle(.plain)
}
}
#Preview {
TestListSelection()
}
Hey everyone,
I’m facing a bug when using UIVisualEffectView in a SwiftUI context via UIViewRepresentable. When the SwiftUI view modifier .blur(radius: xx, opaque: true) is applied to it during rotation, the blur effect isn’t applied. Instead, the view becomes completely white or black, depending on the UIBlurEffect.Style applied to the UIVisualEffectView.
I’m not sure how to proceed with this issue and am seeking your help. Below is a simple, reproducible piece of code:
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Circle()
.fill(.pink)
GlassBackgroundView()
.blur(radius: 7, opaque: true)
}
.ignoresSafeArea()
}
}
#Preview {
ContentView()
}
private struct GlassBackgroundView: UIViewRepresentable {
func makeUIView(context: Context) -> UIVisualEffectView {
UIVisualEffectView(effect: UIBlurEffect(style: .regular))
}
func updateUIView(_ uiView: UIVisualEffectView, context: Context) { }
}
I’m seeing a crash in production for a small percentage of users, and have narrowed it down based on logging to happening as or very shortly after an alert is presented using SwiftUI.
This seems to be isolated to iOS 17.5.1, but since it’s a low-volume crash I can’t be sure there aren’t other affected versions. What can I understand from the crash report?
Here’s a simplified version of the code which presents the alert, which seems so simple I can’t understand why it would crash. And following that is the crash trace.
// View (simplified)
@MainActor public struct MyView: View {
@ObservedObject var model: MyViewModel
public init(model: MyViewModel) {
self.model = model
}
public var body: some View {
myViewContent
.overlay(clearAlert)
}
var clearAlert: some View {
EmptyView().alert(
"Are You Sure?",
isPresented: $model.isClearAlertVisible,
actions: {
Button("Keep", role: .cancel) { model.clearAlertKeepButtonWasPressed() }
Button("Delete", role: .destructive) { model.clearAlertDeleteButtonWasPressed() }
},
message: {
Text("This cannot be undone.")
}
)
}
}
// Model (simplified)
@MainActor public final class MyViewModel: ObservableObject {
@Published var isClearAlertVisible = false
func clearButtonWasPressed() {
isClearAlertVisible = true
}
func clearAlertKeepButtonWasPressed() {
// No-op.
}
func clearAlertDeleteButtonWasPressed() {
// Calls other code.
}
}
Incident Identifier: 36D05FF3-C64E-4327-8589-D8951C8BAFC4
Distributor ID: com.apple.AppStore
Hardware Model: iPhone13,2
Process: My App [379]
Path: /private/var/containers/Bundle/Application/B589E780-96B2-4A5F-8FCD-8B34F2024595/My App.app/My App
Identifier: com.me.MyApp
Version: 1.0 (1)
AppStoreTools: 15F31e
AppVariant: 1:iPhone13,2:15
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: com.me.MyApp [583]
Date/Time: 2024-06-21 20:09:20.9767 -0500
Launch Time: 2024-06-20 18:41:01.7542 -0500
OS Version: iPhone OS 17.5.1 (21F90)
Release Type: User
Baseband Version: 4.50.06
Report Version: 104
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001a69998c0
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler [379]
Triggered by Thread: 0
Kernel Triage:
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
Thread 0 name:
Thread 0 Crashed:
0 libswiftCore.dylib 0x00000001a69998c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144)
1 AttributeGraph 0x00000001d0cd61a4 Attribute.init<A>(body:value:flags:update:) + 352 (Attribute.swift:473)
2 SwiftUI 0x00000001ac034054 closure #1 in Attribute.init<A>(_:) + 128 (<compiler-generated>:0)
3 SwiftUI 0x00000001ac033cac partial apply for closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0)
4 libswiftCore.dylib 0x00000001a6ad0450 withUnsafePointer<A, B>(to:_:) + 28 (LifetimeManager.swift:128)
5 SwiftUI 0x00000001ad624d14 closure #2 in UIKitDialogBridge.startTrackingUpdates(actions:) + 268 (UIKitDialogBridge.swift:370)
6 SwiftUI 0x00000001ad624ae0 UIKitDialogBridge.startTrackingUpdates(actions:) + 248 (UIKitDialogBridge.swift:369)
7 SwiftUI 0x00000001ad6250cc closure #4 in UIKitDialogBridge.showNewAlert(_:id:) + 72 (UIKitDialogBridge.swift:471)
8 SwiftUI 0x00000001abfdd050 thunk for @escaping @callee_guaranteed () -> () + 36 (:-1)
9 UIKitCore 0x00000001aa5722e4 -[UIPresentationController transitionDidFinish:] + 1096 (UIPresentationController.m:651)
10 UIKitCore 0x00000001aa571d88 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke.114 + 320 (UIPresentationController.m:1390)
11 UIKitCore 0x00000001aa5cb9ac -[_UIViewControllerTransitionContext completeTransition:] + 116 (UIViewControllerTransitioning.m:304)
12 UIKitCore 0x00000001aa34a91c __UIVIEW_IS_EXECUTING_ANIMATION_COMPLETION_BLOCK__ + 36 (UIView.m:16396)
13 UIKitCore 0x00000001aa34a800 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 624 (UIView.m:16429)
14 UIKitCore 0x00000001aa349518 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 436 (UIView.m:0)
15 UIKitCore 0x00000001aa356b14 -[UIViewAnimationState animationDidStop:finished:] + 192 (UIView.m:2400)
16 UIKitCore 0x00000001aa356b84 -[UIViewAnimationState animationDidStop:finished:] + 304 (UIView.m:2422)
17 QuartzCore 0x00000001a96f8c50 run_animation_callbacks(void*) + 132 (CALayer.mm:7714)
18 libdispatch.dylib 0x00000001aff61dd4 _dispatch_client_callout + 20 (object.m:576)
19 libdispatch.dylib 0x00000001aff705a4 _dispatch_main_queue_drain + 988 (queue.c:7898)
20 libdispatch.dylib 0x00000001aff701b8 _dispatch_main_queue_callback_4CF + 44 (queue.c:8058)
21 CoreFoundation 0x00000001a808f710 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1780)
22 CoreFoundation 0x00000001a808c914 __CFRunLoopRun + 1996 (CFRunLoop.c:3149)
23 CoreFoundation 0x00000001a808bcd8 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420)
24 GraphicsServices 0x00000001ecf3c1a8 GSEventRunModal + 164 (GSEvent.c:2196)
25 UIKitCore 0x00000001aa6c490c -[UIApplication _run] + 888 (UIApplication.m:3713)
26 UIKitCore 0x00000001aa7789d0 UIApplicationMain + 340 (UIApplication.m:5303)
27 SwiftUI 0x00000001ac27c148 closure #1 in KitRendererCommon(_:) + 168 (UIKitApp.swift:51)
28 SwiftUI 0x00000001ac228714 runApp<A>(_:) + 152 (UIKitApp.swift:14)
29 SwiftUI 0x00000001ac2344d0 static App.main() + 132 (App.swift:114)
30 My App 0x00000001001e7bfc static MyApp.$main() + 52 (MyApp.swift:0)
31 My App 0x00000001001e7bfc main + 64
32 dyld 0x00000001cb73de4c start + 2240 (dyldMain.cpp:1298)
Hi all,
It wasn't extensively covered in the "Unlock the power of places with MapKit" at WWDC, but is it possible to add your own views to the mapItemDetailAccessory? The default view is great, but I would like to add a button for opening a new window showing another view. The documentation is rather limited at the moment so I thought I would ask here.
Thanks in advance.
Summary
When trying to display SwiftUI previews, building the previews may fail with the following error:
Linking failed: linker command failed with exit code 1 (use -v to see invocation)
ld: warning: search path '/Applications/Xcode.app/Contents/SharedFrameworks-iphonesimulator' not found
ld: warning: Could not find or use auto-linked framework 'CoreAudioTypes': framework 'CoreAudioTypes' not found
Note that may app does not use CoreAudioTypes.
Observation
This issue seems to occur when two conditions are met:
The SwiftUI view must be located in a Swift Package
Somewhere in either the View or the #Preview a type from another package has to be used.
Say I have to packages one named Model-package and one named UI-Package. The UI-Package depends on the Model-Package. If I have a SwiftUI view in the UI-Package that uses a type of the Model-Package either in the View itself or in the #Preview, then the described error occurs. If I have a View in the UI-package that does not use a type of the Model-Package anywhere in its View or #Preview then the SwiftUI Preview builds and renders successful.
I created a bug report: FB13033812
I have two (local) Swift packages (both with a single library product): RemoteImage, which defines setImage(from:) function on UIImageView and SatelitUI package which directly depends on the first one and defines some views. But when I'm trying to preview views from the second package I'm getting the following error:
linker command failed with exit code 1 (use -v to see invocation)
LinkDylibError: Failed to build TrailerView.swift
Linking failed: linker command failed with exit code 1 (use -v to see invocation)
ld: warning: directory not found for option '-F/Applications/Xcode-beta.app/Contents/SharedFrameworks-iphonesimulator'
Undefined symbols for architecture x86_64:
"(extension in RemoteImage):__C.UIImageView.setImage(from: Foundation.URL?) -> ()", referenced from:
(extension in SatelitUI_PreviewReplacement_TrailerView_2):SatelitUI.TrailerView.(previewupdate in _8C3731B0EF007627509BEEB93277D681)(with: SatelitUI.Trailer?) -> () in TrailerView.2.preview-thunk.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Apparently, Xcode fails to link the library from the first package because it's dynamic. Static linking works as expected.
It's a bug I believe?
Hi all, I have done a lot of research on this but am not able to come up with a workable solution.
Background:
I am trying to make an universal app on macOS/iOS that organizes media (image/video/pdf); think of its functionality like Apple's Photos app. So for my app document type, I would have my custom file package and within the package folder, there would be a SwiftData model container file and folders to hold user media.
Approaches taken:
DocumentGroup with SwiftData model then write directly into the file package
In my App scene, I create document by having DocumentGroup(editing: .customDocument, migrationPlan: CustomMigrationPlan.self). This will create a document with a model container with my SwiftData model. And when I need to add media files into the document, I get the URL of the document, then use FileManager to write the file into the desired folder in the document. The result is that the media file is saved in the file package but then the SwiftData container is corrupted (all model data is reset to empty.)
I am now trying to:
2. DocumentGroup with custom file package then try to embed SwiftData container
In my current approach, I would create a document by having DocumentGroup(newDocument: CustomFileDocument()). I have custom FileDocument and FileWrapper. But the problem is I don't know how to embed a SwiftData container into my FileDocument. Is it possible to create a SwiftData model container when my FilerWrapper initialize? I can't figure out how to do this.
Can anyone please advice on how I should accomplish this? Or if maybe I am looking at this problem wrongly? Do I need to use AppKit/UIKit with Core Data because it's currently not possible with SwiftUI/SwiftData?
Thank you so much for reading and any input is greatly appreciated.
I'm creating an app where I'm recreating how Apple Maps shows the user location button - i.e, in a stack with a background. I'd like the MapUserLocationButton to follow the styling that it does in Apple Maps (i.e., when locked to the user location, it switches to a filled icon, instead of colouring the background. Is there a way to do this?
I'm trying to convert my project to use Swift 6 with Complete Concurrency in Xcode 16 beta 1.
The project uses TipKit, but I'm getting compile errors when trying to use the TipKit Parameters feature. Here is an example of the type of error I'm seeing (Note that this code from https://developer.apple.com/documentation/tipkit/highlightingappfeatureswithtipkit):
struct ParameterRuleTip: Tip {
// Define the app state you want to track.
@Parameter
static var isLoggedIn: Bool = false
Static property '$isLoggedIn' is not concurrency-safe because it is non-isolated global shared mutable state.
Is there a new pattern for supporting TipKit Parameters in Swift 6 with Complete Concurrency enabled? There is no obvious suggestion for how to fix this.
The latest WWDC 2024 TipKit doesn't appear to have any solution(s).
Is there a way to optimize a List in SwiftUI?
There is a problem with selection not working properly when the List has many rows.
If you scroll to multi-select and up, some rows in the middle are not selected.
I have an issue where selecting an unselected row deselects nearby rows.
Is there any way for selection to work reliably even for a List of many rows?
I would like to find a solution that is stable even when multiple lines are selected, like mail and note, which are the default apps in ios.
ps. I am using CoreData.
@State var selectedItem = Set<MyEntity>()
List(selection: $selectItem){
ForEach(items, id: \.self){ item in
ContactsRow(contactsData: item)
}
}
.environment(\.editMode, $editMode)
I'm developing an application in which saving files and opening them with .quickLookis in important role.
However, after putting my application to TestFlight and letting a friend of mine test it with his phone (iOS 17.4.1, iPhone 15 Pro) it appears that sometimes when opening a file the QuickLook sheet doesn't open until the app's focus is lost.
@State
Button("Open file") {
url = someFileUrl
}.quickLookPreview($url)
I am new to SwiftUI, and I wrote a ReorderableForEach struct with onDrag and onDrop, which is working well on iOS17. However it's not wokring on iOS18 beta1 or beta2 on my iPhone or simulator. When I long press the item, nothing happens.
When I remove onDrop, I can perform a Drag animation, so I think something wrong with my onDrop code.
the whole code:
import UIKit
import SwiftUI
public typealias Reorderable = Identifiable & Equatable
struct GridData: Identifiable, Equatable {
let id: Int
}
public struct ReorderableForEach<Item: Reorderable, Content: View, Preview: View>: View {
@Binding
private var active: Item?
@State
private var hasChangedLocation = false
private let items: [Item]
private let content: (Item) -> Content
private let preview: ((Item) -> Preview)?
private let moveAction: (IndexSet, Int) -> Void
private var onDropAction: ((Item) -> Void)?
private var allowReorder: Bool
public init(
_ items: [Item],
active: Binding<Item?>,
allowReorder: Bool,
@ViewBuilder content: @escaping (Item) -> Content,
@ViewBuilder preview: @escaping (Item) -> Preview,
moveAction: @escaping (IndexSet, Int) -> Void,
onDropAction: ((Item) -> Void)? = nil
) {
self.items = items
self._active = active
self.allowReorder = allowReorder
self.content = content
self.preview = preview
self.moveAction = moveAction
self.onDropAction = onDropAction
}
public init(
_ items: [Item],
active: Binding<Item?>,
allowReorder: Bool,
@ViewBuilder content: @escaping (Item) -> Content,
moveAction: @escaping (IndexSet, Int) -> Void,
onDropAction: ((Item) -> Void)? = nil
) where Preview == EmptyView {
self.items = items
self._active = active
self.allowReorder = allowReorder
self.content = content
self.preview = nil
self.moveAction = moveAction
self.onDropAction = onDropAction
}
public var body: some View {
ForEach(items) { item in
if !allowReorder {
contentView(for: item)
}
else if let preview {
contentView(for: item)
.onDrag {
return dragData(for: item)
} preview: {
preview(item)
}
} else {
contentView(for: item)
.onDrag {
return dragData(for: item)
}
}
}
}
private func contentView(for item: Item) -> some View {
content(item)
.opacity(active == item && hasChangedLocation ? 0.5 : 1)
.onDrop(
of: [.text],
delegate: ReorderableDragRelocateDelegate(
item: item,
items: items,
active: $active,
hasChangedLocation: $hasChangedLocation
) { from, to in
withAnimation {
moveAction(from, to)
}
} onDropAction: { item in
onDropAction?(item)
}
)
}
private func dragData(for item: Item) -> NSItemProvider {
active = item
return NSItemProvider(object: "\(item.id)" as NSString)
}
}
struct ReorderableDragRelocateDelegate<Item: Reorderable>: DropDelegate {
let item: Item
var items: [Item]
@Binding var active: Item?
@Binding var hasChangedLocation: Bool
var moveAction: (IndexSet, Int) -> Void
var onDropAction: ((Item) -> Void)?
func dropEntered(info: DropInfo) {
guard item != active, let current = active else { return }
guard let from = items.firstIndex(of: current) else { return }
guard let to = items.firstIndex(of: item) else { return }
hasChangedLocation = true
if items[to] != current {
moveAction(IndexSet(integer: from), to > from ? to + 1 : to)
}
}
func dropUpdated(info: DropInfo) -> DropProposal? {
DropProposal(operation: .move)
}
func performDrop(info: DropInfo) -> Bool {
hasChangedLocation = false
active = nil
onDropAction?(item)
return true
}
}
struct ReorderableDropOutsideDelegate<Item: Reorderable>: DropDelegate {
@Binding
var active: Item?
func dropUpdated(info: DropInfo) -> DropProposal? {
DropProposal(operation: .move)
}
func performDrop(info: DropInfo) -> Bool {
active = nil
return true
}
}
public extension View {
func reorderableForEachContainer<Item: Reorderable>(
active: Binding<Item?>
) -> some View {
onDrop(of: [.text], delegate: ReorderableDropOutsideDelegate(active: active))
}
}
#Preview {
ReorderableForEach(
(1...10).map { GridData(id: $0) },
active: .constant(nil),
allowReorder: true
) { item in
Text("Item \(item.id)")
.padding()
.background(Color.blue)
.cornerRadius(8)
} preview: { item in
Text("Preview \(item.id)")
.padding()
.background(Color.red)
.cornerRadius(8)
} moveAction: { from, to in
print("Move from \(from) to \(to)")
}
}
Am I missing something or this is a bug on iOS18?
Thanks in advance.
We have an app that is saving UIColor through NSKeyedArchiver.archivedData to a file.
Now we are trying to port the app to a Mac and will like to load the UIColor. But on a Mac, we are using NSColor. Are there any recommendations of what I can do?
When using the Navigation Stack with paths, I've faced an issue where tapping the 'back' button on the custom navigation bar results in a blank screen. With light theme the screen is white, when using dark theme the screen is black. I've found a decision with using an environment value to dismiss a single screen when needed. However, the problem becomes more prominent when I want to pop back to the root view.
This issue has become since updating to iOS 17.
Using the new navigationDestination and NavigationPath functions previously on iOS 16 everything has been working fine using a custom back button, which calls path.removeLast().
However, if we try this on iOS 17, the screen being removed flashes white.
You can try this code as an example (NOTE THE WHITE FLASH ON REMOVE LAST):
struct DetailView: View {
@Binding var path: NavigationPath
var body: some View {
ZStack {
Color.black
VStack(alignment: .center) {
Spacer()
Button(action: {
path.removeLast()
}, label: {
Text("BACK")
})
Spacer()
}
}
}
}
struct ParentView: View {
@State var path: NavigationPath = .init()
var body: some View {
NavigationStack(path: $path) {
ZStack {
Color.red
VStack(alignment: .center) {
Spacer()
Button(action: {
path.append("TEST")
}, label: {
Text("FORWARD")
})
Spacer()
}
}
.navigationDestination(for: String.self) { _ in
DetailView(path: $path)
}
}
}
}
Any work arounds? Suggestions?
I have a horizontal scroll view and a fixed array. I would like to loop it such that when I scroll left and get near the end, the array will add the items in the beginning to the end so that the user can continue to scroll. I would like this to happen when scrolling both left and right and to not have the current position of the user jump around. Here is my code. What am I missing? Would appreciate any and all help.
import SwiftUI
import Algorithms
struct ContentView: View {
@State private var timePosition = ScrollPosition(idType: Int.self, edge: .leading)
@State private var times: [Int] = Array(0...23)
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: 0) {
ForEach(times, id:\.self) { time in
Text("\(time)")
.font(.system(.callout, design: .monospaced, weight: .semibold))
.padding(8)
.frame(width: 180, height: 110, alignment: .topLeading)
.border(width: 1, edges: [.leading, .trailing], color: .primary.opacity(0.05))
.id(time)
}
}
.scrollTargetLayout()
}
.frame(height: 110)
.scrollPosition($timeScrollPosition, anchor: .center)
.onScrollTargetVisibilityChange(idType: Int.self) { timeIDs in
if let currentViewID = model.timeScrollPosition.viewID {
if timeIDs.contains(times[times.count - 2]) {
times.rotate(toStartAt: times.count - 1)
}
if timeIDs.contains(times[1]) {
times.rotate(toStartAt: times.count-1)
}
print("New times: \(times)")
timeScrollPosition.scrollTo(id: currentViewID)
}
}
}
}
Hello,
I am currently developing an app using visionOS, and I am looking for a way to obscure specific content in screenshots. My app includes certain content that is exclusive to premium users, and I need to hide these parts when screenshots are shared on social media.
In iOS, I was able to achieve this by extending SecureField to hide specific Views or Images, but this method does not work in visionOS. I am seeking advice on the best approach to implement this feature in visionOS.
https://github.com/yoxisem544/ScreenshotPreventing-iOS
Specifically, I would appreciate guidance on the following points:
The optimal method for obscuring specific Views or Images in screenshots on visionOS
Any tips or tricks when using existing components similar to SecureField
Techniques or approaches used by other developers to implement similar features
Your assistance would be greatly appreciated. Thank you for your help.
I am currently refactoring my app's side menu to be more like Twitter's. I have the UI down in terms of how the side menu looks and appears, but the issue is navigating to a view from the side menu. The views that a user can go to from the side menu are a mix of SwiftUI views & UIKit View Controllers. As of right now, when a user navigates to a view from the side menu, it presents it modally as a sheet. I want it to have regular navigation, where the user goes to the view displayed in full screen and can tap on the back button to go back to the previous view.
Here is the associated code:
SideMenuView.swift
SideMenuViewModel.swift
How can I modify the navigation logic to be like Twitter's? I've been stuck for days trying to find a fix but it has been a struggle.