Post not yet marked as solved
(Cross post from: Stack Overflow - https://stackoverflow.com/questions/64096402/swiftui-preview-sheet-w-o-running-live-preview)
Is it possible to create a SwiftUI preview of a presented sheet without running the Live Preview? For example:
struct Sheet_Previews: PreviewProvider {
static var previews: some View {
Text("Background").sheet(isPresented: .constant(true)) {
Text("Sheet")
}
}
}
The above results in the following preview:
(See image 1 on Stack Overflow - https://stackoverflow.com/questions/64096402/swiftui-preview-sheet-w-o-running-live-preview)
In order for the sheet content to be presented in the preview, you must run the Live Preview:
(See image 2 on Stack Overflow - https://stackoverflow.com/questions/64096402/swiftui-preview-sheet-w-o-running-live-preview)
Post not yet marked as solved
Hello,
I'm trying to remove the current back button behavior in a navigation view and instead have a simple arrow.
Disabling the button with navigationBarBackButtonHidden and then adding my own with navigationBarItems works, but then I lose the swipe gesture to go back. I could try to rebuild this swipe gesture, but that seems hard to get the same feel, and it will most likely break often.
Is there something simpler ?
I'd be satisfied with just removing the text of the back button and keeping only the <.
Thanks
Post not yet marked as solved
Repro steps: Create new project
Create WidgetKit extension (verify that previews work)
Create dummy framework (verify that previews still work)
Link dummy framework to the widget extension
At that point, preview stops working with the following error:
"RemoteHumanReadableError
ProcessError: Failed to launch widget extension: The operation couldn’t be completed. (CHSErrorDomain error 1050.)"
What can I do to make this work?
Post not yet marked as solved
I'm trying to make a gradient for Widgets and using 2 blue colors (#0091f1 and #0054f3) but the Widget background looks green.
I've set up colors via Assets.xcassets and then using the following code:
LinearGradient(gradient: Gradient(colors: [Color("color1"), Color("color2")]), startPoint: .top, endPoint: .bottom)
For the common iOS target the gradient looks right (blue) and for the Widgets extension it's green.
Could you help me to figure out why this is happening?
The link - https://github.com/maximbilan/SwiftUI-WidgetKit-Gradient-Issue to the example with screenshots.
Post not yet marked as solved
Hey there!
Got a question about font kerning:
When adding a negative kerning to a text (changes via user input) the last character sometimes gets cut off:
dropbox.com/s/49ucdzk8m4k61sj/fontproblem1.png?dl=0
dropbox.com/s/vmklvxp510wjeak/fontproblem2.png?dl=0
What i do is the following:
Text("\(pos, specifier: "%.1f")")
	.font(.system(size: 100,design: .serif))
	.fontWeight(.bold)
	.kerning(-5)
When i remove the kerning it works, but as i understood the kerning keeps the letters as they are? Is there an alternative way of doing it?
Post not yet marked as solved
I'm trying to create a custom Picker similar to the one in the Reminders app where users can select colors and icons for a list of reminders.
I currently have this:
struct CustomPickerStyle: PickerStyle {
static func _makeView<SelectionValue>(value: _GraphValue<_PickerValue<CustomPickerStyle, SelectionValue>>, inputs: _ViewInputs) -> _ViewOutputs where SelectionValue : Hashable {
}
static func _makeViewList<SelectionValue>(value: _GraphValue<_PickerValue<CustomPickerStyle, SelectionValue>>, inputs: _ViewListInputs) -> _ViewListOutputs where SelectionValue : Hashable {
}
}
These are automatically generated by Xcode. How should I deal with these methods? I could not find any documentation online for making a custom picker view...
Thanks!
Post not yet marked as solved
I have a starting view that contains the StateObject created from an Observable Object.
struct PostLoginView: View {
@StateObject var userLoader = FirestoreUser(uid: Auth.auth().currentUser!.uid, getUpdates: true)
var body: some View {
TabView(selection: $currentTab) {
NavigationView{
UserProfileView(currentTab: $currentTab, userLoader: userLoader, postsLoader: postsLoader)
.environmentObject(userSettings)
}
This gets passed to other views where it is observed.
struct UserProfileView: View {
@ObservedObject var userLoader: FirestoreUser
Group{
HStack {
Spacer()
NavigationLink(destination: ProfilePhotoUpdateView(userLoader: self.userLoader).environmentObject(self.userSettings)) {
Image(systemName: "pencil").padding(.horizontal).font(Font.title.weight(.bold))
.foregroundColor(buttonStartColor)
}
}
This chain can continue for a few more links
If the model userLoader is updated in any way, the stack pops back automatically to the first view. This is not the desired behavior. How can I keep the current child view when the model is updated?
Post not yet marked as solved
I've come across some strange behavior with SwiftUI's onAppear() and onDisappear() events. I need to be able to reliably track when a view is visible to the user, disappears, and any other subsequent appear/disappear events (the use case is tracking impressions for mobile analytics).
I was hoping to leverage the onAppear() and onDisappear() events associated with swiftUI views, but I'm not seeing consistent behavior when using those events. The behavior can change depending on view modifiers as well as the simulator on which I run the app.
In the example code listed below, I would expect that when ItemListView2 appears, I would see the following printed out in the console:
button init
button appear
And on the iPhone 8 simulator, I see exactly that.
However, on an iPhone 12 simulator, I see:
button init
button appear
button disappear
button appear
Things get even weirder when I enable the listStyle view modifier:
button init
button appear
button disappear
button appear
button disappear
button appear
button appear
The iPhone 8, however remains consistent and produces the expected result.
I should also note that in no case, did the Button ever seem to disappear and re-appear to the eye.
These inconsistencies are also not simulator only issues, i noticed them on devices as well.
I need to reliably track these appear/disappear events. For example I'd need to know when a cell in a list appears (scrolled into view) or disappears (scrolled out of view) or when, say a user switches tabs.
Has anyone else noticed this behavior? To me this seems like a bug in SwiftUI, but I'm not certain as I've not used SwiftUI enough to trust myself to discern a programmer error from an SDK error. If any of you have noticed this, did you find a good work-around / fix?
Thanks,
Norm
// Sample code referenced in explanation
// Using Xcode Version 12.1 (12A7403) and iOS 14.1 for all simulators
import SwiftUI
struct ItemListView2: View {
		let items = ["Cell 1", "Cell 2", "Cell 3", "Cell 4"]
		var body: some View {
				ListingView(items: items)
		}
}
private struct ListingView: View {
		let items: [String]
		var body: some View {
				List {
						Section(
								footer:
										FooterButton()
										.onAppear { print("button appear") }
										.onDisappear { print("button disappear") }
						) {
								ForEach(items) { Text($0) }
						}
				}
//			.listStyle(GroupedListStyle())
		}
}
private struct FooterButton: View {
		init() {
				print("button init")
		}
		var body: some View {
				Button(action: {}) { Text("Button")	}
		}
}
Post not yet marked as solved
Hi everyone! I recently noticed a strange behaviour with the new SwiftUI Toolbar.
I have an app with only 2 views: a ContentView and a DetailView. My goal is to have a different toolbar in both.
ContentView:
struct ContentView: View {
@State var isFavorite = false
var body: some View {
NavigationView {
VStack {
Image(systemName: isFavorite ? "star.fill" : "star")
NavigationLink(destination: DetailView(isFavorite: $isFavorite)) {
Text("Go")
}
}
.navigationTitle("ContentView")
.toolbar() {
ToolbarItem(placement: .bottomBar) {
Text("This is my ContentView")
}
}
}
}
}
DetailView:
struct DetailView: View {
@Binding var isFavorite: Bool
var body: some View {
Button("Tap me!") {
isFavorite.toggle()
}
.navigationTitle("DetailView")
.toolbar() {
ToolbarItem(placement: .bottomBar) {
Text("This is my DetailView")
}
ToolbarItem(placement: .navigationBarTrailing) {
Image(systemName: isFavorite ? "star.fill" : "star")
}
}
}
}
When I toggle the @Binding property in the DetailView, the toolbar is replaced by another empty toolbar appearing from nowhere.
Am I doing something wrong?
I'm working on an iOS app using SwiftUI and CoreData and am running into a problem that I cannot seem to figure out.
To provide a little bit of information of what I am trying to do:
I have two CoreData entities that have a One-To-Many relationship:
Tarantula - A tarantula may molt many times (To Many) and when deleted, all of the molts shold also be removed (Cascade)
Molt - A molt belongs to a single Tarantula (To One) and when
deleted, should have the reference removed from the Tarantula (Nullify)
I then have a view that lists all of the molts for a given Tarantula that allows adding and deleting molts. It looks like this:
struct MoltListView: View {
		private static let DATE_FORMATTER: DateFormatter = {
						let d = DateFormatter()
						d.dateFormat = "MMM d, y"
						return d
				}()
		
		@Environment(\.managedObjectContext) private var viewContext
		
		@ObservedObject private var tarantula: Tarantula
		@FetchRequest private var molts: FetchedResults<Molt>
		@State private var userMessage: String = ""
		@State private var displayMessage: Bool = false
		
		init(tarantula: Tarantula) {
				self.tarantula = tarantula
				self._molts = FetchRequest(entity: Molt.entity(),
																	 sortDescriptors: [NSSortDescriptor(keyPath: \Molt.date, ascending: false)],
																	 predicate: NSPredicate(format: "tarantula = %@", tarantula))
		}
		
		var body: some View {
				List {
						Section(header: Text("Summary")) {
								Text("\(molts.count) Molt\(molts.count == 1 ? "" : "s")")
						}
						Section(header: Text("Molts")) {
								NavigationLink(destination: MoltView(tarantula: tarantula, molt: Molt.newModel())) {
										Text("Add Molt").foregroundColor(.blue)
								}
								ForEach(molts, id: \.self) { molt in
										NavigationLink(destination: MoltView(tarantula: tarantula, molt: molt)) {
												Text(MoltListView.DATE_FORMATTER.string(from: molt.modelDate))
										}
								}
								.onDelete(perform: deleteItems)
						}
				}.alert(isPresented: $displayMessage) {
						Alert(title: Text("Save Failure"), message: Text(userMessage), dismissButton: .default(Text("Ok")))
				}
		}
		
		private func deleteItems(offsets: IndexSet) {
				withAnimation {
						offsets.map { molts[$0] }.forEach(viewContext.delete)
						do {
								try viewContext.save()
						} catch {
								viewContext.rollback()
								userMessage = "\(error): \(error.localizedDescription)"
								displayMessage.toggle()
						}
				}
		}
}
The error I am experiencing comes from whenever I try to delete a molt from the list view. The app instantly crashes and the error is:
Simultaneous accesses to 0x7f92efc61cb8, but modification requires exclusive access
Find the complete error here:
error - https://developer.apple.com/forums/content/attachment/6d74dcde-d82b-4024-ade0-5936d8926488
I have tried removing the animation block and have played around with removing different UI components/restructuring.
The only way I have been able to prevent this error is to remove the delete rule on the Molt->Tarantula relationship from Nullify to No Action. However, this seems more like a hack to me instead of a fix.
Was hoping for some help on this issue.
Post not yet marked as solved
My view has several textfields for register.
The problem is when I focus on a textfield to update, the text and the caret in the textfield disappeared (but it still stores the value). The text value only appears after the textfield lost keyboard focus.
This error happen with all the devices I have (iPhone 12, iPad), all the simulators I tried. The only thing that works fine is when I using the simulator, I typed in textfield by my Mac physical keyboard instead of simulator's onscreen keyboard.
I'm new in iOS and Swift so please can you help me to resolve this. I could provide UI Hierarchy if needed
Post not yet marked as solved
I am developing an app in swiftUI using Xcode 12.3, deployment target iOS 14.0. The launch screen is setup through info.plist by specifying 'background color' and 'image name'. The file used in 'image name' is from Assets catalog. (PNG format, size300 x 300 and corresponding @2x and @3x resolutions) What I have observed, when the app is installed for the first time the launch image is centered and have original resolutions but all subsequent launches show launch images stretched to cover full screen. Any ideas why this is happening and how to have more consistent behavior either way?
I have tried 'respect safe area' option but it does not make a difference.
Thank you.
I have recently started Beta Testing my SwiftUI App on my iPhone 6s, previously I was testing it on the iPhone 12 Simulator. While Testing on the Real Device I encountered issues like: CPU going past 98%
Really Laggy ScrollView
Tab Bar Freezes Randomly
Since My app is going to go in Production State in a few days, Since this is my first iOS App as well, I am not too sure if these issues are because of SwiftUI, my Phone or what, I have asked Apple Support but, haven't received a response so far.
My App Stats:
Lines of Code: ~1,500
CPU Usage on Simulator: Max. 10%
Bundle Size: 2MB
RAM Max. on Simulator: 32.3mb
Post not yet marked as solved
Hi guys.
I have a question related to the next behavior.
I have ContentView with a list of views where the corresponding view models are passed. The user can click by some view. At the moment full-screen modal dialog will be shown according to the passed type. It's fine.
At some time my view models are being updated and the whole ContentView will be reloaded. The problem is: fullScreenCover is called and ChildEventView is recreated. How to prevent recreating ChildEventView?
struct ContentView: View {
		@ObservedObject private var eventListViewModel = EventListViewModel()
		@State private var fullScreenType: FullScreenType?
		/* some stuff */
		var body: some View {
				ScrollView {
						LazyVStack {
								ForEach(eventListViewModel.cardStates.indices, id: \.self) { index in
										let eventVM = eventListViewModel.eventVMs[index]
										EventCardView(eventViewModel: eventVM, eventId: $selectedEvent.eventId) {
												self.fullScreenType = .type1
										}
										/* some other views */
								}
						}
				}	
				.fullScreenCover(item: $fullScreenType, onDismiss: {
						self.fullScreenType = nil
				}, content: { fullScreenType in
						switch fullScreenType {
								case .type1:
								return ChildEventView(selectedEvent.eventId).eraseToAnyView()
								/* some other cases */
						}
				})
		}
}
Post not yet marked as solved
Hi,
I have embedded a view into a scroll view in case the content is too large, but mostly it is not. Is there a way to have the ScrollView shrink to fit its content?
To my surprise it looks like this is a simple task not possible in SwiftUI? Am I missing something?
All the best
Christoph
Post not yet marked as solved
How do I make a SwiftUI view fullscreen running Mac OS, Catalina or Big Sur?
Post not yet marked as solved
I have been working with UIViewRepresentable a lot recently and noticed something that seems to be quite the flaw:
There doesn't seem to be a clean way of passing data back to your swiftUI views in a performant way.
Here is an example:
struct MapWrapper: UIViewRepresentable {
		@Binding var centerCoordinate: CLLocationCoordinate2D
		init(centerCoordinate: Binding<CLLocationCoordinate2D>) {
				self._centerCoordinate = centerCoordinate
		}
		func makeUIView(context: Context) -> MKMapView {
				var mapView = MKMapView()
				mapView.delegate = context.coordinator
				return mapView
		}
		
		func updateUIView(uiView: MKMapView, context: Context) {
				// Updating the maps center coordinate triggers mapViewDidChangeVisibleRegion, which thus causes updateUIView to trigger again.
				uiView.centerCoordinate = centerCoordinate
		}
		func makeCoordinator() -> Coordinator {
				return Coordinator(parent: self)
		}
		class Coordinator: MKMapViewDelegate {
				var parent: MapWrapper
				init(parent: MapWrapper) {
						self.parent = parent
				}
				func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
						// updating this variable causes a view reload, thus calling updateUIView, and eventually causing this delegate method to trigger again.
						parent.centerCoordinate = mapView.centerCoordinate
}
}
As you can see from the above code, dragging the map anywhere would cause a loop.
The only workaround I have found for this is to give your coordinator a "shouldUpdateState" Boolean variable. and set that prior to updating your bindings.
Has this ever been addressed by apple anywhere? Or are we just expected to only modify our view state from the outside of a UIViewRepresentable?
Post not yet marked as solved
Hello, I connected Universal Links between the website and the application, everything was done according to the official documentation, and everything works fine, when the site is launched, safari offers to launch the application, there is also a banner above the launch page. In SwiftUI, I listen to the URL via .onOpenURL (perform :), everything works, but if the link is encoded in a QR code and scanned through the camera, a plate will appear prompting you to go to the application, and it goes, but only does not pass the URL to the .onOpenURL method (perform: ) . What could be the problem ?
Post not yet marked as solved
Is this a bug or the expected behaviour?
var progress = itemProvider.loadFileRepresentation(
forTypeIdentifier: id,
completionHandler: { [self] (u, error) in
//...
})
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [self] timer in
print("\(progress?.completedUnitCount)/\(progress?.totalUnitCount)")
}
this always prints 100/100
Post not yet marked as solved
Hi,
my app sees quite a lot of crashes (crash report below) and I have no clue how to debug the problem any further.
The problems seems only to occur on macOS 11. Is there anyone als having this kind of problems? Are there fixes/workarounds?
The source code of my app is open source - https://github.com/PDF-Archiver/PDF-Archiver if anyone would like to have a look into it.
OS Version: macOS 11.2.2 (20D80)
Report Version: 104
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: ILL_NOOP at 0x00007fff2ca430f4
Crashed Thread: 0
Application Specific Information:
Fatal error SwiftUI
Thread 0 Crashed:
0 libswiftCore.dylib 0xfffe591310f4 _assertionFailure
1 SwiftUI 0xfffe8516c6fc ViewCache.commitPlacedChildren
2 SwiftUI 0xfffe850727f4 IncrementalChildPlacements.updateValue
3 SwiftUI 0xfffe8512890e Attribute.initT
4 AttributeGraph 0xfffe8625b17e AG::Graph::UpdateStack::update
5 AttributeGraph 0xfffe8625b607 AG::Graph::update_attribute
6 AttributeGraph 0xfffe862638f2 AG::Subgraph::update
7 SwiftUI 0xfffe85463679 GraphHost.runTransaction
8 SwiftUI 0xfffe85464bce GraphHost.runTransaction
9 SwiftUI 0xfffe85463ec8 GraphHost.flushTransactions
10 SwiftUI 0xfffe85464b6e GraphHost.asyncTransactionT
11 SwiftUI 0xfffe85464738 @callee_guaranteed
12 SwiftUI 0xfffe84d172b0 ViewGraphDelegate.updateGraphT
13 SwiftUI 0xfffe853201b9 ViewRendererHost.updateViewGraphT
14 SwiftUI 0xfffe8531e2a8 ViewRendererHost.updateViewGraphT
15 SwiftUI 0xfffe85329e98 NSHostingViewT
16 SwiftUI 0xfffe84d12f06 ViewGraphDelegate.updateGraphT
17 SwiftUI 0xfffe84d17258 NSHostingViewT
18 SwiftUI 0xfffe85464b49 GraphHost.init
19 SwiftUI 0xfffe84d18c9b @callee_guaranteed
20 SwiftUI 0xfffe8537a250 @callee_guaranteed
21 SwiftUI 0xfffe85377ee5 NSRunLoop.flushObservers
22 SwiftUI 0xfffe8537a198 NSRunLoop.addObserver
23 SwiftUI 0xfffe853755fd @callee_guaranteed
24 libswiftObjectiveC.dylib 0xfffe66ed2d9d autoreleasepoolT
25 SwiftUI 0xfffe8537a182 NSRunLoop.addObserver
26 SwiftUI 0xfffe8537a1ca NSRunLoop.addObserver
27 CoreFoundation 0xfffe40ab4dac __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
28 CoreFoundation 0xfffe40ab4c3c __CFRunLoopDoObservers
29 CoreFoundation 0xfffe40ab3745 CFRunLoopRunSpecific
30 HIToolbox 0xfffe5101162f RunCurrentEventLoopInMode
31 HIToolbox 0xfffe5101142b ReceiveNextEventCommon
32 HIToolbox 0xfffe5101114e _BlockUntilNextEventMatchingListInModeWithFilter
33 AppKit 0xfffe45b349b0 _DPSNextEvent
34 AppKit 0xfffe45b33176 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:]
35 AppKit 0xfffe45b25689 -[NSApplication run]
36 AppKit 0xfffe45af996e NSApplicationMain
37 SwiftUI 0xfffe84ab59f3 runApp
38 SwiftUI 0xfffe8534c791 runAppT
39 SwiftUI 0xfffe84ecb09c App.main
40 PDFArchiver 0x2067699b0 [inlined] PDFArchiverApp.$main
41 PDFArchiver 0x2067699b0 main
42 libdyld.dylib 0xfffe40967620 start
Crash Report - https://developer.apple.com/forums/content/attachment/8bc85490-ee29-4233-91e2-63ff3cd0d3b8