Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.

All subtopics
Posts under UI Frameworks topic

Post

Replies

Boosts

Views

Activity

TextKit 2 : replaceContents(in:with:) is not working
I have NsTextList and it has [NsTextListElement], I want to replace an NsTextListElement with other element like NsTextParagraph or NstextListElement or an AttributedString. For some reason the below method is not working at all. And I couldn't find any alternate way of replacing the elements textLayoutManager.replaceContents(in: element.elementRange, with: NSAttributedString(string: "happy"))
2
0
841
Dec ’24
MTKView delegate ownership during view controller transitions
The Problem When transitioning between view controllers that each have their own MTKView but share a Metal renderer backend, we run into delegate ownership conflicts. Only one MTKView can successfully render at a time, since setting the delegate on one view requires removing it from the other, leading to paused views during transitions. For my app, I need to display the same visuals across multiple views and have them all render correctly. Current Implementation Approach I've created a container object that manages the MTKView and its relationship with the shared renderer: class RenderContainer { let metalView: MTKView private let renderer: MetalRenderer func startRendering() { metalView.delegate = renderer metalView.isPaused = false } func stopRendering() { metalView.isPaused = true metalView.delegate = nil } } View controllers manage the rendering lifecycle in their view appearance methods: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) renderContainer.startRendering() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) renderContainer.stopRendering() } Observations & Issues During view controller transitions, one MTKView must stop rendering before the other can start. Also there is no guarantee that the old view will stop rendering before the new one starts, with the current API design. This creates a visual "pop" during animated transitions Setting isPaused = true helps prevent unnecessary render calls but doesn't solve the core delegate ownership problem The shared renderer maintains its state but can only output to one view at a time Questions What's the recommended approach for handling MTKView delegate ownership during animated transitions? Are there ways to maintain visual continuity without complex view hierarchies? Should I consider alternative architectures for sharing the Metal content between views? Any insights for this scenario would be appreciated.
1
0
523
Dec ’24
How to create and manage nested List with NSTextList, NSAttributedString and UI/NSTextView
I am developing a library for RichTextEditor for SwiftUI, and I am facing issues with implementing NSParagraphStyle related features like nested bullet lists and text alignment. I have searched a lot and personally feel that the documentation is not enough on this topic, so here I want to discuss how we can achieve the nested list with UI/NSTextView and natively available NSTextList in NSParagraphStyle.textLists. The problem is I am not able to understand how I can use this text list and how to manage adding list and removing list with my editor I have seen code that work adding attributes to each string and then merge them, but I don't want that, I want to add/update/remove attributes from selected text and if text is not selected then want to manage typing attributes to keep applied attributes to current position
1
0
513
Dec ’24
ios18系统 iPad 从服务器获取的带有透明图片的pdf(Data格式)文档后,document?.dataRepresentation() 转换后,透明图片背景变黑
程序从服务端获取有透明图片的pdf(Data格式)文档后, 通过PDFDocument(data: pdfData!) 加载pdf,显示正常,当我用document?.dataRepresentation()将显示的pdf转换为Data格式后再传给服务端,此时的pdf上的透明图片背景变成黑色了。只有在ios18的iPad上有此问题,ios18以下系统iPad和iPhone无此问题, ios18的iPhone也没有此问题
Topic: UI Frameworks SubTopic: UIKit
0
0
222
Dec ’24
NavigationSplitView does not work inside NavigationStack
When using a NavigationSplitView within a NavigationStack, the NavigationSplitView does not work as expected on iOS 18 (it worked previously). Items do not show their associated detail views when selected. See the following minimum reproducible example: import SwiftUI struct ContentView: View { @State var selectedItem: String? = nil @State var navigationState: NavigationState? = nil var body: some View { NavigationStack { List(selection: self.$selectedItem) { NavigationLink("Item 1", value: "item") } .navigationDestination(item: self.$selectedItem) { value in ChildView() } } } } enum NavigationState: Hashable { case general case secondary } struct ChildView: View { @State var navigationState: NavigationState? = nil var body: some View { NavigationSplitView { List(selection: self.$navigationState) { NavigationLink(value: NavigationState.general) { Text("Basic info") } NavigationLink(value: NavigationState.secondary) { Text("Secondary info") } } } detail: { if self.navigationState == nil { Text("Nothing") } else { Text("Details") } } } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
327
Nov ’24
Is there a way to disable button tap feedback in watchOS double-tap gesture?
First post here! Is there a way to reduce the number of haptic feedback for double tap on primary button? Context: Double tap is awesome. Two haptic actuations are given to the gesture to let the user know that the gesture is "received" then a third haptic feedback is given shortly after to signal the primary button is tapped. Is there a way to disable the third haptic feedback. In other words make primary action "silent"? I have tested a number of apps that supports double tap, it seems to me that the triple tap is a system level default, and it cannot be changed. Any help would be greatly appreciated.
0
0
483
Nov ’24
otential Optimization or Bug in UINavigationController Push Operation in iOS 18
Issue Description: In iOS 18, when setting the root view controller of a UINavigationController and immediately pushing another view controller, the root view controller's lifecycle methods, such as viewDidLoad(), are not called as expected. This issue does not occur in previous iOS versions. There is no mention of this behavior in the iOS 18 release notes, and it is causing significant issues in our application. Steps to Reproduce: Set the root view controller of a UINavigationController. Immediately push another view controller. Observe that the root view controller's lifecycle methods, such as viewDidLoad(), are not called. Example Code: Swift import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("HomeViewController viewDidLoad") } } class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("SecondViewController viewDidLoad") } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let home = HomeViewController() let rootNav = UINavigationController(rootViewController: home) window?.rootViewController = rootNav window?.makeKeyAndVisible() let secondViewController = SecondViewController() home.navigationController?.pushViewController(secondViewController, animated: true) return true } } Expected Behavior: The root view controller's lifecycle methods, such as viewDidLoad(), should be called when setting it as the root view controller of a UINavigationController. Actual Behavior: In iOS 18, the root view controller's lifecycle methods are not called when it is set as the root view controller and another view controller is immediately pushed. Impact: This issue affects the proper initialization and setup of the root view controller, causing significant disruptions in our application's workflow. Device Information: iOS Version: iOS 18 Test Devices: iPhone 15, iPhone 16 Additional Information: We would appreciate any insights or updates on whether this is an intended optimization or a potential bug. This issue is causing significant disruption to our application, and a timely resolution would be greatly appreciated.
3
0
451
Dec ’24
Control gallery preview bug
Environment: Xcode16, iOS 18.1 official version Background: I created a control center widget using a custom sf symbol Phenomenon: When I first installed it, it displayed normally in the control gallery, but when I recompiled and installed it again, the icon disappeared when I looked at it again in the control gallery. I used Console to check the error log and found that its output was' No image named 'my_custom _symbol_name' found in asset catalog for/private/var/containers/Bundle/Application/F977FCFB-DA1C-4924-8613-50531CA2A364/MyDemoApp. app/PlugIns/MyDemoApp Extension. apex '. I found that this uuid was not consistent with the uuid I print during debugging, as if the control gallery had done some kind of caching; Additionally, when I added my Control to the Control Center, it was able to display normally, and the only issue was with the Control Gallery Attempted method: -Using the system SF Symbol, it works fine and can be displayed normally in the control gallery after recompilation. However, once I switch another SF Symbols, the icons in the control gallery do not update after recompilation and installation -Restarting the device, the same issue still persists Is this a system bug or did I make a mistake? Looking forward to someone helping, thank you My Code: @available(iOSApplicationExtension 18.0, *) struct MySearchControlWidget: ControlWidget { let kind = "MySearchControlWidget" let title = "My Title" var body: some ControlWidgetConfiguration { let intent = MyCommonButtonControlWidgetIntent() StaticControlConfiguration(kind: kind) { ControlWidgetButton(action: intent) { Label("\(title)", image:"my_custom_symbol_name") } } .displayName("\(title)") } }
1
0
323
Nov ’24
Possible to have NSWindow *without* NSWindowStyleMaskTitled to make the screen its on the main screen?
I have a NSWindow subclass. The window has a custom shape, and thus has a custom contentView which overrides drawRect to draw . Since the window has a custom shape it cannot use the system provided titlebar. The problem I'm having is when there are multiple screens, if my window is on the inactive screen (not mainScreen with menu bar) and I move the mouse over to the second monitor and click the window....the menu bar doesn't travel to the screen my app is on after the window is clicked. This does not happen with any other window. In all other windows, the menu bar moves to the screen once you click a window on that screen. So it appears this is because my window is not using NSWindowStyleMaskTitled. As far as I know, I can't use the system title bar and draw my custom window shape. Abandoning the custom window shape is not an option. Without going into too many details as to why I care, the menu bar really should travel with first click on my window like other apps.. Is there a way to tell the system (other than using the NSWindowStyleMaskTitled) that clicking on my window should make that screen the "main screen" (bring the menu bar over? I tried programmatically activating the application, ordering the window to the front, etc. but none of this works. This forces the user to click outside my app window, say on the desktop, to move the menu bar over, which feels wrong. Thanks in advance if anyone has any suggestions.
Topic: UI Frameworks SubTopic: AppKit Tags:
5
0
659
Dec ’24
UITableViewDropItem missing in Xcode 16?
Following instructions from ChatGPT, I'm trying to rearrange the order of rows in a UITableView. - (void)tableView:(UITableView *)tableView performDropWithCoordinator:(id<UITableViewDropCoordinator>)coordinator { NSIndexPath *destinationIndexPath = coordinator.destinationIndexPath ?: [NSIndexPath indexPathForRow:self.items.count inSection:0]; [tableView performBatchUpdates:^{ for (UITableViewDropItem *dropItem in coordinator.items) { NSString *movedItem = dropItem.dragItem.localObject; if (movedItem) { NSIndexPath *sourceIndexPath = dropItem.sourceIndexPath; if (sourceIndexPath) { [self.items removeObjectAtIndex:sourceIndexPath.row]; [self.items insertObject:movedItem atIndex:destinationIndexPath.row]; [tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath]; } } } } completion:nil]; } Xcode is complaining that UITableViewDropItem does not exist. The class is in all the documentation, it is just not showing up when needed! Suggestions?
Topic: UI Frameworks SubTopic: UIKit
1
0
316
Nov ’24
Adopt UIFindInteraction across multiple views
We are currently trying to adopt the newly introduced find bar in our app. The app: The app is a text editor with a main text view. However it includes nested views (for text like footnotes) that are presented as modal sheets. So you tap on the footnote within the main text, a form sheet is presented with the contents of the footnote ready to be edited. We have an existing search implementation, but are eager to move to the system-provided UI. Connecting the find bar through a custom UIFindSession with our existing implementation is working without any issues. The Problem: Searching for text does not only work in the main text view, but also nested text (like footnotes). Let's say I have a text containing the word "iPhone" both in the main text and the footnote. In our existing implementation, stepping from the search match to the next one would open the modal and highlight the match in the nested text. The keyboard would stay open. With the new UIFindInteraction this is not working however. As soon as a modal form sheet is presented, the find interaction closes. By looking at the stack trace I can see a private class called UIInputWindowController that cleans up input accessory views after the modal gets presented. I believe it is causing the find panel to give up its first responder state. I noticed that opening popovers appears to be working fine. Is there a way to alter the presentation of the nested text so that the view is either not modal or able to preserve the current find session? Or is this unsupported behavior and we should try and look for a different way? The thing that really confuses me is that this appears to work without issue in Notes.app. There the find bar is implemented as well. There are multiple views that can be presented while the find bar is open. Move Note is one of them. The view appears as a modal sheet. It keeps the find bar open and active, though its tint color matches the deactivated one of the main Notes view. The find bar is still functional with the text field being active and the overlay updating in the background. This behavior appears to be a bug in the Notes app, but is exactly what we want for our use case. I attached some images: Two are from the Notes app, two from a test project demonstrating the problem. Opening a modal view closes the find bar there.
2
0
1.3k
Jan ’25
Wrapping views with a VStack breaks animation, but using an extension to do the same thing fixes it.
I was having issues with views transitioning between being visible and not visible inside of List. They would appear, but the animation would be jerky. I switched to using a Section, and the animation looked much better. However, the spacing between views and padding wasn't what I wanted. So I wrapped some of the views inside the Section with a VStack. But first, this is how my view SectionView looks: struct SectionView<Content: View>: View { let title: String @ViewBuilder var content: () -> Content var body: some View { Section { Text(title) .font(.title3.bold()) content() } .listRowInsets(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20)) .listRowBackground(Color.clear) .listRowSeparator(.hidden) .contentShape(.rect) } } Below was in a separate view: SectionView(title: "Title") { Group { HStack { // Stuff here } if let selectedMonth { VStack(alignment: .leading, spacing: 10) { // Stuff here } } } .animation(.smooth, value: selectedMonth) } This, however, broke the animations again when the VStack appears. It went back to being jerky. So instead of wrapping the content inside of a VStack, I created an extension to do the same thing. extension View { @ViewBuilder func condensed() -> some View { VStack(alignment: .leading, spacing: 10, content: { self }) } } So now instead of wrapping it in a VStack, I do this: if let selectedMonth { Group { // Stuff here } .condensed() } The animations look good again. I just can't figure out why that is. Can anyone help me understand this?
0
0
257
Dec ’24
Scrolling Table with children in SwiftUI for macOS app
How do I scroll to a row and select it when it is part of collapsed rows in Table ScrollViewReader { scrollViewProxy in Table([node], children: \.children, selection: $selectedNodeID) { TableColumn("Key") { Text($0.key) } TableColumn("Value") { Text($0.val) } } .onChange(of: selectedNodeID) { _, newValue in withAnimation { scrollViewProxy.scrollTo(newValue) } } } The code above works well for the rows that are expanded or at the root level. However, for the rows that are not yet expanded the code above does nothing. How can I update the code so that it scrolls to a row that has not materialized yet. Info: This is a macOS app I am on macOS 15.1.1 with Xcode 16.1 and the minimum target of the app is macOS 15
0
0
375
Nov ’24
IKSaveOptions Only Calls its Delegate Once
I use IKSaveOptions to add an accessory view to an NSSavePanel to give the user choice of the image file type (etc) used to save a file. I limit the available file type choices in the accessory's menu by specifying a delegate object that offers the saveOptions:shouldShowUTType: method. Historically, my delegate was called repeatedly (for many file types) so, for those not supported by my code, I was able to omit them from the menu. This is expected behaviour from my interpretation of the documentation for saveOptions:shouldShowUTType: As of Ventura 13.1, the delegate was not called at all; instead, the entire (or at least a long) list of options was offered in the panel. Running the same build of my code on Catalina 10.15.7 still had the historical behaviour. In Sonoma (14.0) the delegate was called exactly once (for JPEG). This behaviour persists in Sequoia 15.1.1 . I have used test code and breakpoints to ensure that I pass a valid reference to my delegate and to inspect when (if) it is called. If there is some (new?) pre-condition for the accessory's use needed on Ventura and later, or a workaround, I would be grateful to be pointed to it.
Topic: UI Frameworks SubTopic: AppKit
0
0
330
Dec ’24
the ID [":"] occurs multiple times within the collection, this will give undefined results!
Hi! After upgrading to Xcode 16.1 my watchOS app is getting below error using a DatePicker configured with: displayedComponents: .hourAndMinute. I cannot find a solution for this error/warning. It only appears when im using : .hourAndMinute or : .hourAndMinuteandSeconds, but not .date. Note! My code is unchanged only change I Xcode upgrade. Any suggestions? ForEach<Array, Array, _ConditionalContent<_ConditionalContent<_ConditionalContent<_ConditionalContent<YearPicker, MonthPicker>, _ConditionalContent<DayPicker, ComponentPicker>>, _ConditionalContent<_ConditionalContent<ComponentPicker, ComponentPicker>, _ConditionalContent<AMPMPicker, ModifiedContent<Text, _PaddingLayout>>>>, EmptyView>>: the ID [":"] occurs multiple times within the collection, this will give undefined results! import SwiftUI import WidgetKit struct TimeEditView: View { let title: String @Binding var storedValue: String var body: some View { Form { DatePicker( title, selection: Binding<Date>( get: { Date.from(storedValue) ?? Date() }, set: { newDate in storedValue = newDate.toString() } ), displayedComponents: .hourAndMinute ) .onChange(of: storedValue) { WidgetCenter.shared.reloadAllTimelines() print("Morning Start changed!") } } .navigationTitle(title) } }
0
0
284
Dec ’24
Suppressing contextual menu on AVPlayerView in SwiftUI app
My app plays videos. At first I used SwiftUI’s VideoPlayer, but that didn't give me enough control over the underlying AVPlayerView, so I created my own NSViewRepresentable. That works well, and I can adjust the AVPlayerView as I see fit. But it seems to have a contextual menu that still appears instead of the one I try to apply using SwiftUI. If I put a non-opaque color over the AVPlayerView in a ZStack, I'm able to then add a .contextMenu that works, but only if the color is non-opaque (e.g. Color(red: 0, green: 0, blue: 0, opacity: 0.00001)). This feels like a pretty hacky solution, and doesn’t work if I set opacity: to 0. Is there a better way to keep AVPlayerView from handling events? It also gets scroll events (which scrubs through the movie) that I'd like to suppress.
Topic: UI Frameworks SubTopic: SwiftUI
0
0
258
Dec ’24
Management of multiple root views in SwiftUI
Hey guys, I'm totally unexperienced in Swift coding and I'm doing my first steps using Swift Playgrounds on my macOS as well as on my iPadOS. I'm setting up a simple App that can be divided in 4 main categories (Splash, Authentication, Content, Setup). Each category (except the Splash as the short intro when running the app) can have a NavigationStack (e. g. switching between login view, register view, forgott password view in authentication). So I thought about having a root view for each of them. My google research gave me lots of ways and hints but it's not clear at all for me if I should and how I should do this. I often read about a RootViewController but I guess that's UIKit stuff and nothing for SwiftUI. Then I read about delegates and such. Then, I read an article that exactly fits my goals and I just liked to get your opinion what you think about this way to solve my plan: First of all, I define a separate class for a appRootManager: final class appRootManager: ObservableObject { enum eRootViews { case Splash, Authentification, Content, Setup } @Published var currentRoot: eRootViews = .Splash } The main app file looks like this: @main struct MyApp: App { @StateObject private var oRootManager = appRootManager() var body: some Scene { WindowGroup() { Group { switch oRootManager.currentRoot { case .Splash: viewSplash() case .Authentification: viewLogin() case .Content: viewContent() case .Setup: viewSetup() } } .environmentObject(oRootManager) .modelContainer(for: [Account.self]) } } } In each of the for root view files (e. g. Splash view) I make the appRootManager addressable and switch the root view by updating the enum value, like for example: struct viewSplash: View { @EnvironmentObject private var oRootManager: appRootManager var body: some View { ZStack { Color.blue .ignoresSafeArea() Text("Hello World") .font(.title) .fontWeight(.semibold) .foregroundColor(.white) } .onAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + 3) { withAnimation(.spring()) {oRootManager.currentRoot = .Authentification} } } } } It works fine and does exactly what I like to have (when I run the app out of Swift Playgrounds). I'm just wondering why it does not work in the App Preview in Swift Playgrounds and this is why I'd like to have your opinion to the way I solve my plan. I'm very happy for any feedback. Thanks a lot in anticipation! Kind regards Kevin
2
0
369
Nov ’24
Mac: TabView sidebar style does not select Tabs from label or image, only whitespace
On MacOS when TabView is in sidebarAdaptable mode: Clicking the Tab directly on the text of its label, or its systemImage, does not actually select the Tab. The only way to select the Tab is to click whitespace around the text, for example to the right side of the text. iOS has behavior better – you can click the text or image to select the Tab. This behavior is really bizarre and not user-friendly. I'm surprised it could even ship like this. Tabs are actually unusable in sidebarAdaptable because users should not have to be explained to that they need to click on whitespace. Am I missing something? Seems almost too strange to be a bug.
Topic: UI Frameworks SubTopic: SwiftUI
0
0
173
Dec ’24
КАК ОТКЛЮЧИТЬ ФУНКЦИЮ «СГРУЗИТЬ НЕИСПОЛЬЗОВАННОЕ ПРИЛОЖЕНИЕ»
Я случайно по рекомендации Apple включил автоматическое сгружение приложений, и у меня попросту нету функции отключить это в настройках, я пользуюсь iPhone 14 Pro iOS 18.2, СРОЧНО ПОДСКАЖИТЕ РЕШЕНИЕ ПРОБЛЕМЫ ПОЖАЛУЙСТА С уважением Martin.
Topic: UI Frameworks SubTopic: General
1
0
5.3k
Dec ’24