Post

Replies

Boosts

Views

Activity

Custom File "New Document" to show template-picker in a document-based app
I am writing a document-based app for macOS using SwiftUI. I want the File menu's New Document command to show a template picker/wizard, and then let the wizard create the document. How do I structure this? Is there documentation? Examples? I tried this pattern @main struct DocDemoApp: App { var body: some Scene { WindowGroup { NewDocWizard() }     DocumentGroup(newDocument: { DocDemoDocument() }) {         ContentView(document: $0.document)     } } } The NewDocWizard calls newDocument({ DocDemoDocument() }). But the WindowGroup makes a File > New Window command while DocumentGroup makes the File > New Document command. I need just New Document and it should show the NewDocWizard.
1
0
1.6k
Jan ’23
Unexpected intents
I haven’t done any work for Intents so I don’t know why iOS is making Siri suggestions for my app. Every now and then, maybe especially in the morning, my iPhone will show a button at the bottom of the Lock Screen with my app icon, the title of a data record from inside my app, and the caption “Siri suggestion”. Tapping it launches my app but that’s it. The app doesn’t show the record. Why is iOS doing this? Is this some half-baked effect of using iCloud data or Swift Data? I can’t release the app with iOS doing this, and adding proper Intent support would delay the release.
1
0
724
Oct ’23
Animate list row height
How can I tell List to animate row height changes? I have a list whose rows may grow or shrink with user actions. When that happens the List is redrawn with the new heights instantly but the contents slide to their new position. It'd be better if the row heights were animated. Since I don't know what a row's height is I can't use the usual .frame(height: self.animate ? 60 : 90) This code demonstrates the problem. struct ContentView: View { @State private var numbers: [Int] = [0,1,2,3] var body: some View { VStack { List { Item(numbers: $numbers) Item(numbers: .constant([9,8,7])) } .font(.largeTitle) HStack { Button { withAnimation { addNumber() }} label: { Text("Add") } Spacer() Button { withAnimation { removeNumber() }} label: { Text("Remove") } } } .padding() } private func addNumber() { numbers.append(numbers.count) } private func removeNumber() { numbers = numbers.dropLast() } } struct Item: View { @Binding var numbers: [Int] var body: some View { VStack { ForEach(numbers, id:\.self) { n in Text("\(n)") } } } }
1
4
1k
Oct ’23
Unit test SwiftData migrations
I'm trying to write a unit test for a SwiftData migration. In the teardown function I delete the SQLite container files, but then the underlying sqlite library complains. There must be a way to gracefully terminate the SwiftData container before I delete the files, but I don't see how. Simplying nil-ifying the references doesn't work. I don't see any obvious close functions, so I hope someone knows a non-obvious function. override func tearDownWithError() throws { // Cleanup resources // -- DOES NOT CLOSE UNDERLYING SQLITE ACCESS -- self.container = nil self.context = nil // Delete database do { try FileManager.default.removeItem(at: self.url) } catch { // Ignore file not found, report everything else. let nserror = error as NSError if nserror.domain != "NSCocoaErrorDomain" && nserror.code == 4 { throw error } } try? FileManager.default.removeItem(at: self.url.deletingPathExtension().appendingPathExtension("store-shm")) try? FileManager.default.removeItem(at: self.url.deletingPathExtension().appendingPathExtension("store-wal")) } I get these errors for .store, store-shm, and .store-wal: BUG IN CLIENT OF libsqlite3.dylib: database integrity compromised by API violation: vnode unlinked while in use: /Users/(ME)/Library/Developer/XCTestDevices/C52F4E12-EB4F-4639-9866-C3A7126155FA/data/Containers/Data/Application/B0EE90C6-B95D-4185-890D-6F20766B9B3B/tmp/test1.store invalidated open fd: 11 (0x11) If the worst comes to the worst, I'll work around it by using a differently-named container for each test, but as they're in tmp they'll get cleaned up for me eventually.
1
0
1k
Feb ’24
tvOS play/pause gesture and non-av views
I have a two-view app where the main view is a procedural animation and a secondary view controls settings for the animation. I want to use Play/Pause to toggle between the views, but can't figure out how to do this. Ideally the main view does not have any visible control and the whole screen can be dedicated to the animation view. Attaching onPlayPauseCommand to the main view does not work. I've also tried managing focus using onFocus without success. I'm open to other ways to toggle between the main and settings views, it's just that Play/Pause seems the most intuitive.
1
0
814
Apr ’24
How can I view the Development-server private data for my iCloud test account in the CloudKit Dashboard?
When developing a CloudKit application, the standard recommendation is to create an iCloud account for testing. That makes a lot of sense as I’d like to keep developing code far from my personal iCloud account. But the CloudKit Dashboard won’t let me view the private database for that account. What do other people do to check their work?* clarification: I mean on the development server, not the production server.
3
0
1.7k
Dec ’22
UICollectionViewCell subclass cannot use backgroundView property?
I made a subclass of UICollectionViewCell and Swift is complaining that I'm not allowed to use superclass properties like bounds, backgroundView or selectedBackgroundView. This very code was given by Appleʼs documentation - https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/changing_the_appearance_of_selected_and_highlighted_cells so I don't understand why it's disallowed. I declared class MyCollectionViewCell: UICollectionViewCell method awakeFromNib. class MyCollectionViewCell: UICollectionViewCell { ... override class func awakeFromNib() { ... let redView = UIView(frame: bounds) redView.backgroundColor =  colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) self.backgroundView = redView let blueView = UIView(frame: bounds) blueView.backgroundColor =  colorLiteral(red: 0, green: 0, blue: 1, alpha: 1) self.selectedBackgroundView = blueView Xcode 12.2 gives an error about bounds, backgroundView, and selectedBackgroundView saying stuff like "Instance member 'bounds' cannot be used on type 'MyCollectionViewCell'". If I declare a variable as UICollectionViewCell I can set these properties in it, but a function in a subclass of UICollectionViewCell cannot access its own properties?
2
0
880
Dec ’20
(Xcode 14.0 beta 5) ThreadSanitizer: CHECK failed: tsan_platform_posix.cpp:83 "((beg)) <= ((end))"
Similarly to this old post [https://developer.apple.com/forums/thread/130969] I am getting a "ThreadSanitizer: CHECK failed" before my code seems to have launched. Is this something I should spend time trying to reproduce in a small project or is it an Xcode bug others are getting too? Turning off the sanitizer is my dirty workaround for now.
2
0
3.0k
Aug ’22
ShareLink FileRepresentation exports message as a file
When I save an item which is a FileRepresentation to the File system/Files app, TWO files are saved: the shared file, and simple text file containing the message text. I don't want the user to get the message in a text file when they save that way. Sure I can just leave out the message parameter, but then it's useful if they want to email the file somewhere? Is there a way to have a message text that isbn't saved in a file? ShareLink(item: ..., subject: Text("..."), message: Text("..."), //⬅ this text gets saved in a 2nd file preview: SharePreview("...", image: ...)) { Label { Text("...") } icon: { Image(systemName: "square.and.arrow.up") } }
2
0
835
Nov ’23
Single window keyboard shortcut
I made a macOS document-based app that has a second scene that's a Window. It's name appears in the single window list of the Windows menu, but has no assigned shortcut. I've tried the following to assign a shortcut to it, but it doesn't add a "⌘L" as I want: Window("Logs", id: "logs") { LogsView() } .keyboardShortcut("l") I can brute-force this using .commands to replace the menu item but that seems crude and unnecessary. Is it the only way?
2
0
476
Jan ’25
searchable: Add an auxilliary search view
Is there a clean way to add an auxilliary view to the SwiftUI .searchable view? The best I have found is to add a VStack above the list being searched, but this makes the removal transition behave funny. ("Funny" means the search view and aux views animate away fine, but after they finish animating the List view snaps to the top of the screen, hiding the idle search field. The normal behavior leaves the idle search field showing.) NavigationStack { MyListView().searchable(...) } ——— struct MyListView: View { @Environment(\.isSearching) private var isSearching var body: some View { if isSearching { VStack {...my auxilliary view...} } List {...} } }
Topic: UI Frameworks SubTopic: SwiftUI
3
0
450
Sep ’24
Define Array of protocol which conforms to Identifiable
I've got Yet Another Protocol Question. Sorry, folks.The Swift 5.1 manual describes creating a `Collection` where the `Element` is a simple protocol, but doesn't explain how to make a Collection where the Element is a protocol with an associatedtype. In my case it's a protocol `Playable` that requires conformance to `Identifiable`.I am fine with requiring the `Identifiable.ID` type to be `Int` for all types which adopt `Playable`, but I don't know how to express that qualification/requirement. The bits hit the fan when I try to declare something to be `[Playable]`.My playground code might make my question clear.protocol Playable: Identifiable // DOESN'T WORK where ID: Int { // DOESN'T HELP associatedtype ID = Int // DOESN'T HELP var id: Int { get } func play() } struct Music: Playable { var id: Int func play() { print("playing music #\(id)") } } (Music(id: 1)).play() // displays: "playing music #1\n" class Game: Playable { var id: Int init(id: Int) { self.id = id } func play() { print("playing game #\(id)") } } (Game(id: 2)).play() // displays: "playing game #2\n" enum Lottery: Int, Playable { case state = 100 case church case charity var id: Int { return self.rawValue } func play() { print("playing lottery \(self) #\(self.rawValue)") } } Lottery.church.play() // displays: "playing lottery church #101\n" var stuff: [Playable] = [] // error: Protocol 'Playable' can only be used as a generic constraint because it has Self or associated type requirements stuff.append(Music(id: 10)) stuff.append(Game(id: 24)) stuff.append(Lottery.charity) stuff.map { $0.id }My goal is to have different structs and classes conforming to Playable (and hence to Identifiable) able to live inside a Collection.
7
1
7.6k
Nov ’22
Dragging list rows between sections
I am making an iPhone-first app which has a 2 level data structure. I want the user to be able to drag List rows from section to section, but not reorder the sections. Is there a SwiftUI way to do it, or should I resort to UIKit? The basic problem seems to be that ForEach.onMove only allows reordering within its nearest datasource. That seems sensible as a general facility. As it stands now drags can only happen within a section. Swift ForEach(groups) { group in Section(header: Text(group.text)) { ForEach(group.items) { item in Text(item.text) } } } .onMove { … } I might be willing to dive into UIKit to get this done, if it'll handle it. Right now I've flattened the data and marked some items as "containers" and others as "leaves". All get emitted as a dumb flat list: Swift ForEach(items) { item in if item.isContainer { Text(item.text).bold() } else { Text(item.text) } } .onMove { … } The major downside is users can move the container "section header" lines. Drag and drop doesn't seem to work on iPhone, just iPads. I'm kinda shy about hierarchical lists using List(_,children:) because I expect move would still allow top level items (my containers) would be allowed to be moved.
4
0
5.5k
Jul ’21