Post

Replies

Boosts

Views

Activity

SwiftUI: TextField not getting focus changes inside Button
I have a SwiftUI List (on macOS) where I want to display a few TextFields in each row, and observe how the focus changes as an individual text field is selected or unselected. This seems to work fine if I just have the List display a pure TextField in each row, but if I embed the TextField inside a Button view, the focus change notifications stop working. I want the 'button' functionality so that the user can tap anywhere on the row and have the text field activated, instead of tapping exactly on the text field boundary. Here is some code to demonstrate the problem. In the List if you have RowView uncommented out (1), then the focus change notifications work. If you comment that out and uncomment the RowViewWithButton (2), then the button functionality works, but I can't get focus change notifications anymore. Here is the code to reproduce the issue. Interestingly, when I test this on iOS, it works fine in both cases. But I need the solution for macOS. import SwiftUI // test on macOS target struct ContentView: View { @State private var textFields = Array(repeating: "", count: 4) @FocusState private var focusedField: Int? var body: some View { List(0..<4, id: \.self) { index in // 1. works with focus notification changes RowView(index: index, text: $textFields[index], focusedField: $focusedField) // 2. button works, but no focus notifications on text field //RowViewWithButton(index: index, text: $textFields[index], focusedField: $focusedField) } } } struct RowView: View { let index: Int @Binding var text: String @FocusState.Binding var focusedField: Int? var body: some View { HStack { Text("Row \(index + 1):") TextField("", text: $text) .multilineTextAlignment(.leading) .focused($focusedField, equals: index) } .onChange(of: focusedField) { newFocus in if newFocus == index { print("TextField \(index) is in focus") } else { print("TextField \(index) lost focus") } } .padding(.vertical, 4) } } struct RowViewWithButton: View { let index: Int @Binding var text: String @FocusState.Binding var focusedField: Int? var body: some View { Button (action: { print("RowView - button selected at index \(index)") focusedField = index }) { HStack { Text("Row \(index + 1):") TextField("", text: $text) .multilineTextAlignment(.leading) .focused($focusedField, equals: index) } .onChange(of: focusedField) { newFocus in if newFocus == index { print("TextField \(index) is in focus") } else { print("TextField \(index) lost focus") } } .foregroundColor(.primary) } .buttonStyle(BorderlessButtonStyle()) .padding(.vertical, 4) } } #Preview { ContentView() .frame(width: 320, height: 250) }
2
0
127
1d
SwiftUI 'List' performance issue on macOS
Hi, When using SwiftUI ‘List’ with a large number of elements (4000+), I noticed a significant performance issue if extracting the views inside the ‘ForEach’ block into their own subview class. It affects scrolling performance, and using the scroll handle in the scrollbar causes stutters and beachballs. This seems to happen on macOS only ... the same project works fine on iOS. Here's an example of what I mean: List (selection: $multiSelectedContacts) { ForEach(items) { item in // 1. this subview is the problem ... replace it with the contents of the subview, and it works fine PlainContentItemView(item: item) // 2. Uncomment this part for it to work fine (and comment out PlainContentItemView above) /*HStack { if let timestamp = item.timestamp, let itemNumber = item.itemNumber { Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)") } }*/ } } struct PlainContentItemView: View { let item: Item var body: some View { HStack { if let timestamp = item.timestamp, let itemNumber = item.itemNumber { Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)") } } } } Item is a NSManagedObject subclass, and conforms to Identifiable by using the objectID string value. With this, scrolling up and down using the scrolling handle, causes stuttering scrolling and can beachball on my machine (MacBook Pro M1). If I comment out the ‘PlainContentItemView’ and just use the HStack directly (which is what was extracted to ‘PlainContentItemView’), the performance noticeably improves, and I can scroll up and down smoothly. Is this just a bug with SwiftUI, and/or can I do something to improve this?
2
0
538
Oct ’24
SwiftUI: Major unannounced change in iOS18.4 beta1
Hi, I have noticed a major change to a SwiftUI API behavior in iOS18.4beta1 which breaks my app's functionality, and I've started hearing from users running the new beta that the app doesn't correctly work for them anymore. The problem is with views that contain a List with multiple-selection, and the contextMenu API applied with the ‘primaryAction’ callback that is triggered when the user taps on a row. Previously, if the user tapped on a row, this callback was triggered with the 'selectedItems' showing the tapped item. With iOS18.4beta, the same callback is triggered with ‘selectedItems’ being empty. I have the code to demonstrate the problem: struct ListSelectionTestView: View { @State private var items: [TimedItem] = [ TimedItem(number: 1, timestamp: "2024-11-20 10:00"), TimedItem(number: 2, timestamp: "2024-11-20 11:00"), TimedItem(number: 3, timestamp: "2024-11-20 12:00") ] @State var selectedItems = Set<TimedItem.ID>() var body: some View { NavigationStack { List(selection: $selectedItems) { ForEach(items) { item in Text("Item \(item.number) - \(item.timestamp)") } } .contextMenu(forSelectionType: TimedItem.ID.self, menu: {_ in Button(action: { print("button called - count = \(selectedItems.count)") }) { Label("Add Item", systemImage: "square.and.pencil") } }, primaryAction: {_ in print("primaryAction called - count = \(selectedItems.count)") }) } } } struct TimedItem: Identifiable { let id = UUID() let number: Int let timestamp: String } #Preview { ListSelectionTestView() } Running the same code on iOS18.2, and tapping on a row will print this to the console: primaryAction called - count = 1 Running the same code on iOS18.4 beta1, and tapping on a row will print this to the console: primaryAction called - count = 0 So users who were previously selecting an item from the row, and then seeing expected behavior with the selected item, will now suddenly tap on a row and see nothing. My app's functionality relies on the user selecting an item from a list to see another detailed view with the selected item's contents, and it doesn't work anymore. This is a major regression issue. Please confirm and let me know. I have filed a feedback: FB16593120
3
0
248
1w
SwiftUI Transformable: support drag to Finder on macOS
I am trying to support dragging out a 'file' object from my app into Finder, on macOS. I have my object conform to Transferable and the files are saved on disk locally, so I just want to pass it the URL. This works fine when dragging out to other apps, like Notes or Mail, but not in Finder. I setup a ProxyRepresentation as well, as suggested by another thread, but it doesn't seem to help. Is there any other setup I need to do in the Xcode project file for it to work, or is there something else that I'm missing? @available(iOSApplicationExtension 17.0, macOSApplicationExtension 14.0, *) extension FileAttachments: Transferable { public static var transferRepresentation: some TransferRepresentation { FileRepresentation(exportedContentType: UTType.content) { content in SentTransferredFile(content.fullFileURL(), allowAccessingOriginalFile: false) } .exportingCondition { file in if let fileUTI = UTType(filenameExtension: file.fullFileURL().pathExtension), let fileURL = file.fullFileURL() { print("FileAttachments: FileRepresentation exportingCondition fileUTI: \(fileUTI) for file: \(fileURL)") return fileUTI.conforms(to: UTType.content) } return false } .suggestedFileName{$0.fileRenamedName} ProxyRepresentation { file in if let fileURL = file.fullFileURL() { print("FileAttachments: ProxyRepresentation returning file") return fileURL } return file.fullFileURL()! } } }
1
0
234
3w
NSApplicationDelegate openURLs never called
Hi, I have an existing AppKit-based Mac app that I have been working on for a few years. For a new feature, I wanted to have the app opened by a different app, so I setup the URL scheme under CFBundleURLTypes in my Info.plist, and adopted this delegate callback:   - (void)application: (NSApplication *)application openURLs:(nonnull NSArray<NSURL *> *)urls Now when I invoke the URL from the 2nd app, it opens my app correctly, BUT this delegate method isn't called. What's interesting is that if I make a totally new app with a URL scheme and adopt this delegate method, it gets called without a problem! SO what about my original project could be responsible for this 'opensURLs' method to not be called? I've been searching for a solution for a couple of days without any luck. The macOS app's target has a Deployment Target of 10.15 and I'm running this on macOS12.0 with Xcode 13.
2
0
715
Nov ’21
Crash in iOS18
I have a UITableView which contains a UICollectionView in the first row. It used to work fine in iOS17, but now I get a crash when running with Xcode 16 / iOS18 beta: Expected dequeued view to be returned to the collection view in preparation for display. When the collection view's data source is asked to provide a view for a given index path, ensure that a single view is dequeued and returned to the collection view. Avoid dequeuing views without a request from the collection view. For retrieving an existing view in the collection view, use -[UICollectionView cellForItemAtIndexPath:] or -[UICollectionView supplementaryViewForElementKind:atIndexPath:] This is my UITableView delegate call: AddEditDataCell *cell = nil; if (indexPath.section == 0) { if (indexPath.row == 0) { AddEditDataContactsCell *contactNameCell = (AddEditDataContactsCell *)[self cellForContactNamesCollectionAtIndexPath:indexPath tableView:tableView]; return contactNameCell; - (AddEditDataContactsCell *)cellForContactNamesCollectionAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView { AddEditDataContactsCell *contactsCell = (AddEditDataContactsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"ContactsCell" forIndexPath:indexPath]; if (self.collectionNameCell == nil) { self.collectionNameCell = [contactsCell.collectionView dequeueReusableCellWithReuseIdentifier:@"LogContactNameCollectionCellIdentifier" forIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; contactsCell.nameCellDelegate = self; } contactsCell.frame = CGRectZero; [contactsCell setNeedsLayout]; [contactsCell.collectionView reloadData]; contactsCell.collectionViewHeightConstraint.constant = contactsCell.collectionView.collectionViewLayout.collectionViewContentSize.height; [contactsCell.collectionView.collectionViewLayout invalidateLayout]; return contactsCell; }
27
19
21k
Jun ’24
NSOutlineView with Diffable Data Source
Hi, On macOS, there seems to be a NSTableViewDiffableDataSource and an NSCollectionViewDiffableDataSource, but there seems to be nothing for NSOutlineView. Is it possible to somehow use NSTableViewDiffableDataSource with NSOutlineView that I'm missing? If not, is it possible to use NSTableView with NSTableViewDiffableDataSource to show a 'table' with section headers?
5
0
530
Dec ’24
Image Playground API
Hi, WWDC24 videos have a lot of references to an "Image Playground" API, and the "What's New in AppKit" session even shows it in action, with a "ImagePlaygroundViewController". However, there doesn't seem to be any access to the new API, even with Xcode 16.2 beta. Am I missing something, or is that 'coming later'?
5
1
1.1k
Nov ’24
Contacts: remove member from group not working on macOS
Hi, In my app, I have an option to remove a contact from a contact group (using the Contacts framework), and it's been working fine till recently users of the macOS version reported that it's not working. I have been using the CNSaveRequest removeMember(contact, from: group) API. The same API works fine on iOS. I'm not sure when it started but it seems to be affecting macOS14.6 as well as 15.1. I was able to reproduce it in a small test project as well, and have the same experience (the API works on iOS but not on macOS), so it definitely seems like a problem with the framework. Can someone confirm this, and/or suggest a workaround? Here's the code I run to test it out ...a simple SwiftUI view that has 4 buttons: Create contact and group Add contact to group Remove contact from group (optional) cleanup by deleting contact and group It's the 3rd step that seems to fail on macOS, but works fine on iOS. Here's the code to test it out: struct ContentView: View { let contactsModel = ContactsStoreModel() var body: some View { VStack (alignment: .center, spacing: 15){ Button ("1. Add Contact And Group") { print("add contact button pressed") contactsModel.addTestContact() if let _ = contactsModel.createdContact { print("created contact success") } } Button ("2. Add Contact To Group") { print("add to group button pressed") contactsModel.addContactToGroup() } Button ("3. Remove Contact From Group") { print("remove from group button pressed") contactsModel.removeContactFromGroup() } Button ("4. Delete Contact and Group") { print("remove from group button pressed") contactsModel.deleteContactAndGroup() } } .padding() } } #Preview { ContentView() } @available(iOS 13.0, *) @objc final class ContactsStoreModel: NSObject, ObservableObject { let contactStore = CNContactStore() var createdContact : CNContact? var createdGroup : CNGroup? public func addTestContact() { let storeContainer = contactStore.defaultContainerIdentifier() let contact = CNMutableContact() contact.givenName = "Testing" contact.familyName = "User" contact.phoneNumbers = [CNLabeledValue(label: "Cell", value: CNPhoneNumber(stringValue: "1234567890"))] let group = CNMutableGroup() group.name = "Testing Group" print("create contact id = \(contact.identifier)") print("create group id = \(group.identifier)") do { let saveRequest = CNSaveRequest() saveRequest.transactionAuthor = "TestApp" saveRequest.add(contact, toContainerWithIdentifier: storeContainer) saveRequest.add(group, toContainerWithIdentifier: storeContainer) try contactStore.execute(saveRequest) createdContact = contact createdGroup = group } catch { print("error in store execute = \(error)") } } public func addContactToGroup() { if let contact = createdContact, let group = createdGroup { do { let saveRequest = CNSaveRequest() saveRequest.transactionAuthor = "TestApp" saveRequest.addMember(contact, to: group) try contactStore.execute(saveRequest) } catch { print("error in store execute = \(error)") } } } public func removeContactFromGroup() { if let contact = createdContact, let group = createdGroup { do { let saveRequest = CNSaveRequest() saveRequest.transactionAuthor = "TestApp" saveRequest.removeMember(contact, from: group) try contactStore.execute(saveRequest) } catch { print("error in store execute = \(error)") } } } public func addGroupAndContact() { let storeContainer = contactStore.defaultContainerIdentifier() let group = CNMutableGroup() group.name = "Test Group" print("create group id = \(group.identifier)") if let contact = createdContact { do { let saveRequest = CNSaveRequest() saveRequest.transactionAuthor = "TestApp" saveRequest.add(group, toContainerWithIdentifier: storeContainer) saveRequest.addMember(contact, to: group) try contactStore.execute(saveRequest) createdGroup = group } catch { print("error in store execute = \(error)") } } } public func deleteContactAndGroup() { if let contact = createdContact, let group = createdGroup { do { let mutableGroup = group.mutableCopy() as! CNMutableGroup let mutableContact = contact.mutableCopy() as! CNMutableContact let saveRequest = CNSaveRequest() saveRequest.transactionAuthor = "TestApp" saveRequest.delete(mutableContact) saveRequest.delete(mutableGroup) try contactStore.execute(saveRequest) } catch { print("error in deleting store execute = \(error)") } } } }
1
0
389
Nov ’24
Intents not showing up in Shortcuts app
I have an existing iOS app with shortcuts support, and I am trying to bring the same shortcuts to my Mac app in macOS Monterey. In my case, I have added the same intents definition file to my Mac target app, added "Intents eligible for in-app handling" to my Info.plust file and added the intent names, and made sure all the intent handling code is part of both iOS and Mac targets. Still, when I build and run the app on macOS Monterey, the new shortcuts don't show in the shortcut editor at all. I've tried closing and restarting the Shortcuts app, but no luck. The build logs do show the intents being built, but they're just not showing up in the Shortcuts app. I tried 'donating' one of the intents in my Mac app code, but got an error: Cannot donate interaction with intent that has no valid shortcut types Not sure what to try to make it work. Thanks.
4
0
2.1k
Oct ’21
UIDocumentPickerViewController: open to specific folder
Hi, With UIDocumentPickerViewController, there is a directoryURL property that says we can use to 'specify the starting directory for the document picker'. But it's not clear how to get the directory of a folder in iCloud Drive / Files app. How can I get the 'root' directory for a user's iCloud Drive or Dropbox folder, or the Downloads folder on their device, that I could pass to this directoryURL to make it easier for the user to pick their files? Thanks.
0
0
357
Nov ’24
Disable new tab bar look
Hi, I am trying out the new UITabBar stuff in iOS18, and I don't think it'll be a good fit for my app. Is there a way to revert to the old iPad UITabBar look and placement that we've been using before? I don't want to make such a big change like this just yet, but I would need to make other changes to the app as well and I don't want to use the new UITabBar just yet. Is there a way to achieve this?
32
18
18k
Jun ’24
App Groups and macOS 15
Hi, I just updated my machine to macOS 15, and while developing and running my app (with Xcode), I keep getting messages about my app "would like to access data from other apps". This happens even from Xcode Previews, so it's pretty annoying. My production app doesn't seem to be affected by this problem; the system prompt just pops when running the debug version. I came across something about App Groups in macOS and how something has changed in macOS15 regarding system permissions. I use the "group.***" prefix in my macOS app, without the team prefix. Is that the problem here? But why is my production app working fine, but the development app is triggering the prompt repeatedly? Would love any feedback or workarounds. Thanks.
7
1
770
Oct ’24
New crashes with NSOutlineView in MacOS Sequoia
Hi, I have noticed a major uptick in crash reports, ever since I updated my app for macOS Sequoia. All of them have to do with NSOutlineView, and they all have a similar internal API in the crash log, which shows that the issue is something to do with the framework. They all have references to NSConcreteMapTable and _TtCs12_SwiftObject isEqual. The issue isn't reproducible, but it's reported by many different users, all on macOS15+, and it was never an issue with macOS14 or below, so I'm not sure what to do about it. Here's a couple of examples of the new crash reports: Date/Time: 2024-10-29T06:55:19.999Z Launch Time: 2024-10-29T06:50:08Z OS Version: Mac OS X 15.0.1 (24A348) Report Version: 104 Exception Type: SIGTRAP Exception Codes: TRAP_BRKPT at 0x1a98c9c90 Crashed Thread: 0 Thread 0 Crashed: 0 libswiftCore.dylib 0x00000001a98c9c90 -[_TtCs12_SwiftObject isEqual:] + 240 1 Foundation 0x0000000199ad4e0c probeGC + 408 2 Foundation 0x0000000199b01e6c -[NSConcreteMapTable removeObjectForKey:] + 76 3 AppKit 0x000000019c5966a8 _NSOVFreeRowEntry + 44 4 AppKit 0x000000019c5965c4 _NSOVRecursiveFreeChildrenAndItem + 100 5 AppKit 0x000000019c59649c _NSOVFastRemoveChildRowEntries + 260 6 AppKit 0x000000019c595d40 -[NSOutlineView reloadItem:reloadChildren:] + 1016 7 MyApp 0x0000000104b454fc CJ_CRM.MacCJSidebarViewController.compareContactsDictionariesForPublicGroups() -> () (MacCJSidebarViewController.swift:1611) 8 MyApp 0x0000000104b44518 $s20MyApp26MacCJSidebarViewControllerC27contactsChangedNotificationyySo14NSNotificationCFySo7NSTimerCYbcfU_ (MacCJSidebarViewController.swift:461) 9 MyApp 0x0000000104ba5310 $sSo7NSTimerCIeghg_ABIeyBhy_TR (<compiler-generated>:0) 10 Foundation 0x0000000199b64cfc __NSFireTimer + 100 11 CoreFoundation 0x0000000198988184 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 28 12 CoreFoundation 0x0000000198987e28 __CFRunLoopDoTimer + 1008 13 CoreFoundation 0x0000000198987938 __CFRunLoopDoTimers + 352 14 CoreFoundation 0x000000019896d0f0 __CFRunLoopRun + 1852 15 CoreFoundation 0x000000019896c334 CFRunLoopRunSpecific + 568 16 HIToolbox 0x00000001a3da50cc RunCurrentEventLoopInMode + 288 17 HIToolbox 0x00000001a3daaebc ReceiveNextEventCommon + 632 18 HIToolbox 0x00000001a3dab020 _BlockUntilNextEventMatchingListInModeWithFilter + 72 19 AppKit 0x000000019c4b0a70 _DPSNextEvent + 656 20 AppKit 0x000000019cdd67b8 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 684 21 AppKit 0x000000019c4a3b7c -[NSApplication run] + 476 22 AppKit 0x000000019c47a44c NSApplicationMain + 884 23 MyApp 0x0000000104a1e26c main (main.m:24) 24 ??? 0x0000000198504274 0x0 + 0 Another one with a different trigger but same internal API: Date/Time: 2024-10-29T16:49:12.999Z Launch Time: 2024-10-29T15:51:27Z OS Version: Mac OS X 15.1 (24B83) Report Version: 104 Exception Type: SIGSEGV Exception Codes: SEGV_MAPERR at 0x4cde11282080 Crashed Thread: 0 Thread 0 Crashed: 0 libswiftCore.dylib 0x00000001a04efa1c isSubclass(swift::TargetMetadata<swift::InProcess> const*, swift::TargetMetadata<swift::InProcess> const*) + 28 1 libswiftCore.dylib 0x00000001a04ef9f8 _swift_class_isSubclass + 12 2 libswiftCore.dylib 0x00000001a04ffa9c -[_TtCs12_SwiftObject isEqual:] + 252 3 Foundation 0x00000001906b4cec probeGC + 408 4 Foundation 0x00000001906b4adc -[NSConcreteMapTable objectForKey:] + 64 5 AppKit 0x00000001930f8eec -[NSOutlineView _rowEntryForItem:requiredRowEntryLoadMask:] + 48 6 AppKit 0x00000001930f8e80 -[NSOutlineView parentForItem:] + 24 7 MyApp 0x0000000100e2faec MyApp.MacCJSidebarViewController.outlineView(_: __C.NSOutlineView, selectionIndexesForProposedSelection: Foundation.IndexSet) -> Foundation.IndexSet (MacCJSidebarViewController.swift:759) 8 MyApp 0x0000000100e30dbc @objc MyApp.MacCJSidebarViewController.outlineView(_: __C.NSOutlineView, selectionIndexesForProposedSelection: Foundation.IndexSet) -> Foundation.IndexSet (<compiler-generated>:0) 9 AppKit 0x000000019324c4e4 -[NSTableView _userSelectableRowIndexesForProposedSelection:userCanAlreadyChangeSelection:] + 288 10 AppKit 0x00000001933176c4 -[NSTableView _userSelectRowIndexes:withNewSelectedRow:] + 140 11 AppKit 0x00000001933175a0 -[NSTableView _userSelectSingleRow:] + 76 12 AppKit 0x0000000193315c8c -[NSTableView mouseDown:] + 2536 13 AppKit 0x0000000193315120 -[NSOutlineView mouseDown:] + 72 14 MyApp 0x0000000100dabb38 -[CustomNSOutlineView mouseDown:] (CustomNSOutlineView.m:180) 15 AppKit 0x000000019320d98c forwardMethod + 248 16 AppKit 0x000000019320d98c forwardMethod + 248 17 AppKit 0x0000000193213518 -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] + 3668 18 AppKit 0x000000019319f00c -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 380 19 AppKit 0x000000019319ecbc -[NSWindow(NSEventRouting) sendEvent:] + 280 20 AppKit 0x00000001939b6bf0 -[NSApplication(NSEventRouting) sendEvent:] + 1652 21 AppKit 0x00000001935c489c -[NSApplication _handleEvent:] + 56 22 AppKit 0x000000019306ab08 -[NSApplication run] + 516 23 AppKit 0x0000000193041364 NSApplicationMain + 884 24 MyApp 0x0000000100d0626c main (main.m:24) 25 ??? 0x000000018f0e4274 0x0 + 0 I just created a Feedback FB15625970. Please let me know if this is a known issue, and/or if there's any ideas out there on how I can do to avoid this. It's causing a lot of instability in my app, that wasn't there before macOS15, so something changed in the internal APIs, and hopefully there's a way to work around it.
0
0
439
Oct ’24