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

How to steal focus from another app's text field?
I have written a calculator app. Its main window is a UIView subclass that usually receives user input from the touchscreen, tapping on a virtual keyboard (not the standard pop-up keyboard). I recently added hardware keyboard support. In order to receive key events, I implemented canBecomeFirstResponder and made it always return YES, and I'm calling becomeFirstResponder whenever the main window becomes active, and resignFirstResponder when it becomes inactive. This is working fine except for one scenario: when running the app on an iPad, together with another app, using Split View or Slide Over, and the other app has keyboard focus on a text field, my app doesn't receive keyboard events, even when it's the foreground app. I have to go into the other app, and tap somewhere outside a text field, and then return to my app, before my app is getting key events again. If the user taps on an actual text field in my app, it gets focus just fine, of course, but apparently my UIView calling becomeFirstResponder is not enough to take away the focus from the other app. Is there a way to steal the focus from another app's text field in this scenario?
Topic: UI Frameworks SubTopic: UIKit
0
0
305
Dec ’24
UIContextMenuInteraction not working if view is originally offscreen
I’m having a weird UIKit problem. I have a bunch of views in a UIScrollView and I add a UIContextMenuInteraction to all of them when the view is first loaded. Because they're in a scroll view, only some of the views are initially visible. The interaction works great for any of the views that are initially on-screen, but if I scroll to reveal new subviews, the context menu interaction has no effect for those. I used Xcode's View Debugger to confirm that my interaction is still saved in the view's interactions property, even for views that were initially off-screen and were then scrolled in. What could be happening here?
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
86
Mar ’25
view controller life cycle bug in xcode 16 ios 18
hi does any one know if there changes in lifecycle in xcode 16 ios 18 cause i notice that my view will appear does what view didappear use to do in older version and it kind of a problem cause all the rest of ios work diffrently does anyone else found a problem with it? or does anyone know if there was a known change to life cycles
0
0
429
Jan ’25
iOS 18.4 App updates crashes the widget and the only solution is to restart the device or change the device language
App update in which there were no changes regarding the widget. Just after it updated, the widget turns black in some cases. It also appears black in the widget gallery. Removing and adding it again did not work in this case, only after an iOS restart it works fine again This is the log 2025-03-20 02:14:05.961611 +0800 Content load failed: unable to find or unarchive file for key: [com.aa.bb::com.aa.bb.widget:cc_widget:systemMedium::360.00/169.00/23.00:(null)~(null)] on no host. The session may still produce one shortly. Error: Using url file:///private/var/mobile/Containers/Data/PluginKitPlugin/51C5E4F2-6F1F-4466-A428-73C73B9CC887/SystemData/com.apple.chrono/placeholders/cc_widget/systemMedium----360.00w--169.00h--23.00r--1f--0.00t-0.00l-0.00b0.00t.chrono-timeline ... Error Domain=NSCocoaErrorDomain Code=4 "file“systemMedium----360.00w--169.00h--23.00r--1f--0.00t-0.00l-0.00b0.00t.chrono-timeline”not exist。" UserInfo={NSFilePath=/private/var/mobile/Containers/Data/PluginKitPlugin/51C5E4F2-6F1F-4466-A428-73C73B9CC887/SystemData/com.apple.chrono/placeholders/cc_widget/systemMedium----360.00w--169.00h--23.00r--1f--0.00t-0.00l-0.00b0.00t.chrono-timeline, NSUnderlyingError=0xa693d3a80 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
0
0
98
Mar ’25
iPadOS 18 App (on Apple Silicon) - Duplicate Tab Bar Appearing in Toolbar
With iPadOS 18, the UITabBar now defaults to the floating style. I successfully reverted the tab bar to its traditional style by overriding the UITabBarController's horizontalSizeClass property: self.tabBarController?.traitOverrides.horizontalSizeClass = .unspecified When I launch the app on my Mac using Apple Silicon, TWO tab bars appear: One appears at the bottom of the screen, like a traditional tab bar. The second tab bar is still embedded in the app toolbar in its floating style. Is this a bug? How do you ensure that overriding the horizontalSizeClass will remove/hide the floating tab bar when running an app on Apple Silicon? TIA! (Demonstrated on a test project)
0
0
484
Jan ’25
Regarding errors with UIToolbar and UIBarButtonItem set to UITextField
I set UIToolbar and UIBarButtonItem to UITextField placed on Xib, but when I run it on iOS18 iPad, the following error is output to Xcode Console, and UIPickerView set to UITextField.inputView is not displayed. Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API and this value is being ignored. Please fix this problem. If you want to see the backtrace, please set CG_NUMERICS_SHOW_BACKTRACE environmental variable. Backtrace: <CGPathAddLineToPoint+71> <+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadii:segments:smoothPillShapes:clampCornerRadii:] <+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadius:segments:]+175> <+[UIBezierPath _roundedRectBezierPath:withRoundedCorners:cornerRadius:segments:legacyCorners:]+338> <-[_UITextMagnifiedLoupeView layoutSubviews]+2233> <__56-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]_block_invoke+89> <+[UIView(UIViewAnimationWithBlocksPrivate) _modifyAnimationsWithPreferredFrameRateRange:updateReason:animations:]+166> <block_destroy_helper.269+92> <block_destroy_helper.269+92> <__swift_instantiateConcreteTypeFromMangledName+94289> <block_destroy_helper.269+126> <+[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:anima <block_destroy_helper.269+6763> <block_destroy_helper.269+10907> <-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]+389> <-[_UITextMagnifiedLoupeView setVisible:animated:completion:]+256> <-[UITextLoupeSession _invalidateAnimated:]+329> <-[UITextRefinementTouchBehavior textLoupeInteraction:gestureChangedWithState:location:translation:velocity: <-[UITextRefinementInteraction loupeGestureWithState:location:translation:velocity:modifierFlags:shouldCanc <-[UITextRefinementInteraction loupeGesture:]+701> <-[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:]+71> <_UIGestureRecognizerSendTargetActions+100> <_UIGestureRecognizerSendActions+306> <-[UIGestureRecognizer _updateGestureForActiveEvents]+704> <_UIGestureEnvironmentUpdate+3892> <-[UIGestureEnvironment _updateForEvent:window:]+847> <-[UIWindow sendEvent:]+4937> <-[UIApplication sendEvent:]+525> <__dispatchPreprocessedEventFromEventQueue+1436> <__processEventQueue+8610> <updateCycleEntry+151> <_UIUpdateSequenceRun+55> <schedulerStepScheduledMainSection+165> <runloopSourceCallback+68> <__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__+17> <__CFRunLoopDoSource0+157> <__CFRunLoopDoSources0+293> <__CFRunLoopRun+960> <CFRunLoopRunSpecific+550> <GSEventRunModal+137> <-[UIApplication _run]+875> <UIApplicationMain+123> <__debug_main_executable_dylib_entry_point+63> 10d702478 204e57345 Type: Error | Timestamp: 2025-03-09 00:22:46.121407+09:00 | Process: FurusatoLocalCurrency | Library: CoreGraphics | Subsystem: com.apple.coregraphics | Category: Unknown process name | TID: 0x5c360 Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x600002202a30 h=--& v=--& _UIToolbarContentView:0x7fc2c6a5b8f0.width == 0 (active)>", "<NSLayoutConstraint:0x600002175e00 H:|-(0)-[_UIButtonBarStackView:0x7fc2c6817b10] (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>", "<NSLayoutConstraint:0x600002175e50 H:[_UIButtonBarStackView:0x7fc2c6817b10]-(0)-| (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>", "<NSLayoutConstraint:0x6000022019f0 'TB_Leading_Leading' H:|-(8)-[_UIModernBarButton:0x7fc2a5aa8920] (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>", "<NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>", "<NSLayoutConstraint:0x600002201e50 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.leading == _UIButtonBarButton:0x7fc2f57117f0.leading (active)>", "<NSLayoutConstraint:0x600002201ea0 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.trailing == UIView:0x7fc2a5aac8e0.trailing (active)>", "<NSLayoutConstraint:0x6000022021c0 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2f57117f0]-(0)-[UIView:0x7fc2a5aa8330] (active)>", "<NSLayoutConstraint:0x600002202210 'UISV-spacing' H:[UIView:0x7fc2a5aa8330]-(0)-[_UIButtonBarButton:0x7fc2a5aa84d0] (active)>", "<NSLayoutConstraint:0x600002202260 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2a5aa84d0]-(0)-[UIView:0x7fc2a5aac8e0] (active)>", "<NSLayoutConstraint:0x600002176f30 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>", "<NSLayoutConstraint:0x600002176e40 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide']-(0)-|(LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
107
Mar ’25
SwiftUI Canvas Text - scale to fill rectangle
How do I draw a single line of text in a SwiftUI Canvas, scaled to fill a given rectangle? Example: Canvas { context, size in let r = CGRect(origin: CGPointZero, size: size); // Whole canvas let t = Text("Hello World"); context.draw(t, in: r); } Outside of Canvas I'd add .minimumScaleFactor(0) .lineLimit(1), and I guess set a large default font size, and I'd get the result I want. But inside Canvas, .minimumScaleFactor and .lineLimit don't seem to be available; they return some View, not Text, which can't be used in context.draw. (Is there a trick to make that work?) I have written the following to do this, but I think there must be an easier way to achieve this! Suggestions? extension GraphicsContext { mutating func draw_text_in_rect(string: String, rect: CGRect) { let text = Text(string) .font(.system(size: 25)); // The font size used here does matter, because e.g. letter spacing // varies with the font size. let resolved = resolve(text); let text_size = resolved.measure(in: CGSize(width: CGFloat.infinity, height: CGFloat.infinity)); let text_aspect = text_size.width / text_size.height; let fit_size = CGSize(width: min(rect.size.width, rect.size.height*text_aspect), height: min(rect.size.height, rect.size.width/text_aspect)); let fit_rect = CGRect(x: rect.origin.x + (rect.size.width-fit_size.width)/2, y: rect.origin.y + (rect.size.height-fit_size.height)/2, width: fit_size.width, height: fit_size.height); let scale = fit_size.width / text_size.width; // For debug: // var p = Path(); // p.addRect(fit_rect); // stroke(p, with: GraphicsContext.Shading.color(.red), lineWidth: 1); translateBy(x: fit_rect.minX, y: fit_rect.minY); scaleBy(x:scale, y:scale); draw(resolved, at: CGPointZero, anchor: UnitPoint.topLeading); transform = CGAffineTransformIdentity; } };
0
0
368
Jan ’25
SwiftUI: .searchable displays incorrectly in child views under NavigationStack
There appears to be a visual bug when using .searchable in a child view that’s pushed via NavigationLink inside a NavigationStack. Specifically, the search bar appears briefly in the wrong position (or animates in an unexpected way) during the transition to the child view. This issue does not occur when using NavigationView instead of NavigationStack. Steps to Reproduce: Create a TabView with a single tab containing a NavigationStack. Push from a ContentView to a DetailsView using NavigationLink. Add a .searchable modifier to both the ContentView and DetailsView. Run the app and tap a row to navigate to the details view. Expected Behavior The search bar in the DetailsView should appear smoothly and in the correct position as the view transitions in, just like it does under NavigationView. Actual Behavior When the DetailsView appears, the search bar briefly animates or appears in the wrong location before settling into place. This results in a jarring or buggy visual experience. Feedback: FB17031212 Here is a reddit thread discussing the issue as well https://www.reddit.com/r/SwiftUI/comments/137epji/navigation_stack_with_search_bar_has_a_bug_and_a/ I hope that an Apple engineer can get this fixed soon. It's frustrating to have new APIs come out with the old deprecated yet there are still obvious bugs two years later. import SwiftUI public enum Tab { case main } struct AppTabNavigation: View { @State private var tabSelection = Tab.main var body: some View { TabView(selection: $tabSelection) { NavigationStack { ContentView() } .tag(Tab.main) .tabItem { Label("Main", systemImage: "star") } } } } struct ContentView: View { @State private var searchText = "" var body: some View { List(0..<100) { i in NavigationLink("Select \(i)", value: i) } .navigationTitle("Main") .searchable(text: $searchText) .navigationDestination(for: Int.self) { i in DetailsView(i: i) } } } struct DetailsView: View { @State private var searchText = "" let i: Int // MARK: - Body var body: some View { List { ForEach(0..<10, id: \.self) { i in Text("Hello \(i)") } } .navigationTitle(i.formatted()) .searchable(text: $searchText) } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
69
Mar ’25
How to truncate text from head with multi line?
I want to truncate text from head with max 2 lines. I try the following code import SwiftUI struct ContentView: View { @State var content: String = "Hello world! wef wefwwfe wfewe weweffwefwwfwe wfwe" var body: some View { VStack { Text(content) .lineLimit(nil) .truncationMode(.head) .frame(height: 50) Button { content += content } label: { Text("Double") } .buttonStyle(.borderedProminent) } .frame(width: 200, height: 1000) .padding() } } #Preview { ContentView() } It show result like this, this is not what I want.
0
0
242
Mar ’25
PasteButton in a confirmationDialog
Hey, Anyone knows of a possible way to present a PasteButton in a .confirmationDialog on iOS? when I try adding it, it's ignored and not displayed with the rest of the buttons struct MyView: View { @State var flag: Bool = false var body: some View { Text("Some Text") .confirmationDialog("Dialog", isPresented: $flag) { Group { Button("A") {} Button("B") {} PasteButton(payloadType: Data.self) { data in } } } } }
0
0
147
Mar ’25
Animation Issue: SwiftUI View Not Animating Height Changes in UIHostingController
Hello, I’m developing an app where I display a SwiftUI view inside a UIHostingController embedded within a UIKit ViewController. I’m trying to animate the height of the UIHostingController’s view based on a switch’s value, but the SwiftUI view doesn’t animate at all. Below is a simplified version of my code: class ViewController: UIViewController { private lazy var parentView: UIView = { let view = UIView() view.backgroundColor = .red view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var hostingView: UIView = { let testView = TestView() let hostingController = UIHostingController(rootView: testView) let view = hostingController.view! view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var button: UISwitch = { let button = UISwitch() button.addTarget(self, action: #selector(onClickSwitch(sender:)), for: .valueChanged) button.translatesAutoresizingMaskIntoConstraints = false return button }() private var hostingViewHeightConstraint: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() view.addSubview(parentView) parentView.addSubview(hostingView) parentView.addSubview(button) NSLayoutConstraint.activate([ parentView.topAnchor.constraint(equalTo: view.topAnchor), parentView.bottomAnchor.constraint(equalTo: view.bottomAnchor), parentView.leadingAnchor.constraint(equalTo: view.leadingAnchor), parentView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) NSLayoutConstraint.activate([ hostingView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor), hostingView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor), hostingView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor) ]) hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: 0.5) hostingViewHeightConstraint?.isActive = true NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: parentView.centerXAnchor), NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: parentView, attribute: .centerY, multiplier: 0.25, constant: 0) ]) } @objc func onClickSwitch(sender: UISwitch) { hostingViewHeightConstraint?.isActive = false let multiplier: CGFloat = sender.isOn ? 0.25 : 0.5 hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: multiplier) hostingViewHeightConstraint?.isActive = true UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() } } } I’m looking for the behavior demonstrated in the video below: Does anyone have suggestions on how to achieve this?
0
1
181
Mar ’25
Crash: KEY_TYPE_OF_DICTIONARY_VIOLATES_HASHABLE_REQUIREMENTS
Hi everyone, frome time to time I see crash which Im not able to debug, because there is no line of my code where crash occured. This is a crash log what Im getting from time to time of some users. In my device I never get this kind of crash. 0 libswiftCore.dylib 0x1172c _assertionFailure(_:_:flags:) + 208 1 libswiftCore.dylib 0x198624 KEY_TYPE_OF_DICTIONARY_VIOLATES_HASHABLE_REQUIREMENTS(_:) + 2980 2 libswiftCore.dylib 0xdb6c8 specialized _NativeDictionary.uncheckedRemove(at:isUnique:) + 534 3 libswiftCore.dylib 0xb250c Dictionary._Variant.setValue(_:forKey:) + 204 4 libswiftCore.dylib 0x5a620 Dictionary.subscript.setter + 520 5 SwiftUICore 0xf62ec ForEachState.item(at:offset:) + 4340 6 SwiftUICore 0xf5054 ForEachState.forEachItem(from:style:do:) + 1796 7 SwiftUICore 0x2272f8 ForEachState.traitKeys.getter + 84 8 SwiftUICore 0x227298 ForEachList.traitKeys.getter + 24 9 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76 10 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76 11 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76 12 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76 13 SwiftUICore 0x2271fc DynamicViewList.WrappedList.traitKeys.getter + 88 27 SwiftUICore 0x226d18 specialized static SectionAccumulator.processUnsectionedContent(list:contentSubgraph:) + 84 28 SwiftUI 0x26afe0 ListSectionInfo.init(list:listAttribute:contentSubgraph:) + 132 29 SwiftUI 0x269bb0 UpdateCollectionViewListCoordinator.updateValue() + 1528 30 SwiftUI 0x785d4 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 32 31 AttributeGraph 0xccac AG::Graph::UpdateStack::update() + 540 32 AttributeGraph 0xc870 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424 33 AttributeGraph 0xc444 AG::Subgraph::update(unsigned int) + 848 34 SwiftUICore 0x805a8 GraphHost.flushTransactions() + 860 35 SwiftUI 0x1ac84 closure #1 in _UIHostingView._renderForTest(interval:) + 24 36 SwiftUICore 0x7ffa8 partial apply for closure #1 in ViewGraphDelegate.updateGraph<A>(body:) + 28 37 SwiftUICore 0x7fd6c ViewRendererHost.updateViewGraph<A>(body:) + 120 38 SwiftUICore 0x7fce8 ViewGraphDelegate.updateGraph<A>(body:) + 84 39 SwiftUI 0x3e688 closure #1 in closure #1 in closure #1 in _UIHostingView.beginTransaction() + 172 40 SwiftUI 0x3e5d4 partial apply for closure #1 in closure #1 in closure #1 in _UIHostingView.beginTransaction() + 24 41 SwiftUICore 0x79720 closure #1 in static Update.ensure<A>(_:) + 56 42 SwiftUICore 0x796a4 static Update.ensure<A>(_:) + 100 43 SwiftUI 0x9c808 partial apply for closure #1 in closure #1 in _UIHostingView.beginTransaction() + 80 44 SwiftUICore 0x7f5e0 thunk for @callee_guaranteed () -> () + 28 45 SwiftUICore 0x6161c specialized closure #1 in static NSRunLoop.addObserver(_:) + 144 46 CoreFoundation 0x218a4 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 36 47 CoreFoundation 0x213f8 __CFRunLoopDoObservers + 552 48 CoreFoundation 0x75da8 __CFRunLoopRun + 948 49 CoreFoundation 0xc8284 CFRunLoopRunSpecific + 588 50 GraphicsServices 0x14c0 GSEventRunModal + 164 51 UIKitCore 0x3ee674 -[UIApplication _run] + 816 52 UIKitCore 0x14e88 UIApplicationMain + 340 53 SwiftUI 0x291ef8 closure #1 in KitRendererCommon(_:) + 168 54 SwiftUI 0x291e28 runApp<A>(_:) + 100 55 SwiftUI 0x291d0c static App.main() + 180 56 DholRainbow 0x3019e8 main + 4339145192 (DholRainbowApp.swift:4339145192) 57 ??? 0x1b0bf5de8 (Missing) From Crashlytics I know at least human readable format of this error Fatal error: Duplicate keys of type 'Contact' were found in a Dictionary. This usually means either that the type violates Hashable's requirements, or that members of such a dictionary were mutated after insertion. I 've checked all my parts of code where Im using dictionary. This is a function which creating that particulary dictionary. private func logsByDate() { let groupedByDate = Dictionary(grouping: logs.filter { ($0.remoteParty as? Contact != nil) } ) { $0.date.removeTimeStamp ?? .distantPast }.mapValues { $0.compactMap { $0 } } var dayLogs = [DayLog]() for date in groupedByDate { var contacts = [CallLogContact]() for log in logs.filter({ $0.date.removeTimeStamp ?? .distantPast == date.key }) { if let contact = log.remoteParty as? Contact { if contacts.firstIndex(where: {$0.contact == contact }) == nil { let contactDayLogs = logs.filter({ $0.remoteParty as? Contact == contact && $0.date.removeTimeStamp == date.key}) contacts.append( CallLogContact( contact: contact, logs: contactDayLogs, lastCallLogDate: contactDayLogs.sorted(by: {$0.date > $1.date}).first?.date ?? .distantPast ) ) } } } dayLogs.append(DayLog(date: date.key, contact: contacts)) } DispatchQueue.main.async { self.groupedCallLogs = dayLogs } } This function is called from 3 others functions based on notification from the server in case of new call log, fetched call logs and removed call logs.
0
0
270
Mar ’25
SwiftUI Tabview - how to "kill" the views we do not use
I have the MainView as the active view if the user is logged in(authenticated). the memory allocations when we run profile is pretty good. We have graphql fetching, we have token handling eg: This is All heap: 1 All Heap & Anonymous VM 13,90 MiB 65408 308557 99,10 MiB 373965 Ratio: %0.14, %0.86 After what i have checked this is pretty good for initialise and using multiple repositories eg. But when we change tabs: 1 All Heap & Anonymous VM 24,60 MiB 124651 543832 156,17 MiB 668483 Ratio: %0.07, %0.40 And that is not pretty good. So i guess we need to "kill" it or something. How? I have tried some techniques in a forum this was a recommended way: public struct LazyView<Content: View>: View { private let build: () -> Content @State private var isVisible = false public init(_ build: @escaping () -> Content) { self.build = build } public var body: some View { build() Group { if isVisible { build() } else { Color.clear } } .onAppear { isVisible = true } .onDisappear { isVisible = false } } } But this did not help at all. So under here is the one i use now. So pleace guide me for making this work. import DIKit import CoreKit import PresentationKit import DomainKit public struct MainView: View { @Injected((any MainViewModelProtocol).self) private var viewModel private var selectedTabBinding: Binding<MainTab> { Binding( get: { viewModel.selectedTab }, set: { viewModel.selectTab($0) } ) } public init() { // No additional setup needed } public var body: some View { NavigationStack(path: Binding( get: { viewModel.navigationPath }, set: { _ in } )) { TabView(selection: selectedTabBinding) { LazyView { FeedTabView() } .tabItem { Label("Feed", systemImage: "house") } .tag(MainTab.feed) LazyView { ChatTabView() } .tabItem { Label("Chat", systemImage: "message") } .tag(MainTab.chat) LazyView { JobsTabView() } .tabItem { Label("Jobs", systemImage: "briefcase") } .tag(MainTab.jobs) LazyView { ProfileTabView() } .tabItem { Label("Profile", systemImage: "person") } .tag(MainTab.profile) } .accentColor(.primary) .navigationDestination(for: MainNavigationDestination.self) { destination in switch destination { case .profile(let userId): Text("Profile for \(userId)") case .settings: Text("Settings") case .jobDetails(let id): Text("Job details for \(id)") case .chatThread(let id): Text("Chat thread \(id)") } } } } } import SwiftUI public struct LazyView<Content: View>: View { private let build: () -> Content public init(_ build: @escaping () -> Content) { self.build = build } public var body: some View { build() } }
0
0
195
Mar ’25
SwiftUI: How to change `contentInset` of `List`
Hi, Is there any way of changing the contentInset (UIKit variant) of a List in SwiftUI? I do not see any APIs for doing so, the closest I gotten is to use safeAreaInset . While visually that works the UX is broken as you can no longer "scroll" from the gap made by the .safeAreaInset(edge:alignment:spacing:content:) I have subbmited a feedback suggestion: FB16866956
0
0
173
Mar ’25
Monitoring of the paste(GUI based) operation
I am working on the EndPoint DLP solution project. So I want to monitor the paste operation peformed by the user. So when he uses the keyboard keys then I can monitor them using the event callback. But if user uses the GUI for pasting the data then how can I monitor that ?
Topic: UI Frameworks SubTopic: General
0
0
219
Jan ’25
detecting modifier keys using UITextFieldDelegate protocol
I have a UITextField in my application, and I want to detect all the keys uniquely to perform all relevant task. However, there is some problem in cleanly identifying some of the keys. I m not able to identify the backspace key press in the textField(_:shouldChangeCharactersIn:replacementString:) method. Also I don't know how to detect the Caps Lock key. I am intending to so this because I want to perform some custom handling for some keys. Can someone help me with what is the way of detecting it under the recommendation from apple. Thanks in advance. Note: checking for replacementString parameter in shouldChangeCharactersIn method for empty does not help for backspace detection as it overlaps with other cases.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
143
Mar ’25
AppKit: presentAsModalWindow doesn't center the presented window on macOS 15
When I present a view controller, whose view is a SwiftUI View, via presentAsModalWindow(_:) the presented window is no longer centered horizontally to the screen, but rather its origin is there. I know this issue occurs for macOS 15.2+, but can't tell if it is from 15.0+. I couldn't find any documentation on why was this changed. Here's an example code that represents my architecture: class RootViewController: NSViewController { private lazy var button: NSButton = NSButton( title: "Present", target: self, action: #selector(presentView)) override func viewDidLoad() { super.viewDidLoad() // Add button to tree } @objc func presentView() { presentAsModalWindow(PresentedViewController()) } } class PresentedViewController: NSViewController { override loadView() { view = NSHostingView(rootView: MyView()) } } struct MyView: View { /* impl */ }
Topic: UI Frameworks SubTopic: AppKit Tags:
0
0
171
Mar ’25
SensorKit Data Not Retrieving
I have received permission from Apple to access SensorKit data for my app. I have granted all necessary permissions, but no data is being retrieved. The didCompleteFetch method is being called, but I’m unsure where to find event data like Device Usage and Ambient Light. Additionally, the didFetchResult method is never called. Could anyone please assist me in resolving this issue? Any guidance or troubleshooting steps would be greatly appreciated. import SensorKit class ViewController: UIViewController, SRSensorReaderDelegate { let store = SRSensorReader(sensor: .deviceUsageReport) override func viewDidLoad() { super.viewDidLoad() requestSensorAuthorization() } func requestSensorAuthorization() { var sensors: Set<SRSensor> = [ .accelerometer, .deviceUsageReport, .messagesUsageReport, .visits, .keyboardMetrics, .phoneUsageReport, .ambientLightSensor ] if #available(iOS 16.4, *) { sensors.insert(.mediaEvents) } SRSensorReader.requestAuthorization(sensors: sensors) { error in if let error = error { print("Authorization failed: \(error.localizedDescription)") } else { self.store.startRecording() self.requestSensorData() print("Authorization granted for requested sensors.") } } } func requestSensorData() { let fromTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().addingTimeInterval(-60 * 60).timeIntervalSinceReferenceDate) let toTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().timeIntervalSinceReferenceDate) let request = SRFetchRequest() request.from = fromTime request.to = toTime request.device = SRDevice.current store.fetch(request) store.delegate = self } func sensorReader(_ reader: SRSensorReader, didCompleteFetch fetchRequest: SRFetchRequest) { print("Fetch request completed: \(fetchRequest.from) to \(fetchRequest.to)") Task { do { let samples = try await reader.fetch(fetchRequest) print("Samples count: \(samples)") } catch { print("Error Fetching Data: \(error.localizedDescription)") } } } func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, didFetchResult result: SRFetchResult<AnyObject>) -> Bool { print(result) return true } }
0
0
188
Mar ’25
Do the coordinates obtained by scanning a QR code with VNDetectBarcodesRequest match the coordinates of the finder pattern?
I am creating an application that uses VNDetectBarcodesRequest to read QR codes from images and adjust the image orientation to match that of the QR code finder pattern. The QR code was successfully read, and the coordinates of the QR code were obtained.Upon checking the obtained topLeft, topRight, and bottomLeft coordinates, they always seem to match the topLeft, topRight, and bottomLeft coordinates of the finder pattern. Is it specified that the coordinates of topLeft, topRight, and bottomLeft obtained with VNDetectBarcodesRequest match the topLeft, topRight, and bottomLeft of the finder pattern? Or do they just happen to match? I would appreciate it if you could tell me if the matching of coordinates is a specification. Thank you for your help.
0
0
320
Feb ’25
Removing sidebar divider in NavigationSplitView
Hi, I’m practicing with NavigationSplitView for macOS and customizing the sidebar. I’ve managed to adjust most parts, but I couldn’t remove the sidebar’s divider. It seems like it’s not possible in modern SwiftUI. My AppKit knowledge is also not very strong. How can I remove the sidebar divider? I want to use a plain background. I also solved it by creating my own sidebar, but I wanted to try it using NavigationSplitView.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
194
Mar ’25