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
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
AppClip card keeps showing up
After the user clicks the Open button in the AppClip card, the AppClip launches, but the card keeps appearing whenever the user clicks Open. It doesn’t disappear until the user clicks the Close button on the card. This issue started appearing two months ago and only occurs on iOS 17.6 and 17.7. [demo video](https://drive.google.com/file/d/1vJ-7E5JSdO_xoVkDYxBJDkj8sm-dvxv1/view?usp=share_link
Topic: UI Frameworks SubTopic: General
0
0
171
Feb ’25
PhoneSceneDelegate white screen
I am currently implementing multiple scenes in my React Native / Swift application (one scene for the phone and one scene for CarPlay). I am facing an issue where one scene renders completely white (on the iPhone) but I can see in the console that the code is running (for example if I add a console.log to the App.tsx I can see that console log happen in XCode). There are no errors when building the app in XCode, and testing with the simulator CarPlay appears to render the correct output, but there is no component being rendered on the simulated phone screen (just white). AppDelegate.swift import CarPlay import React import React_RCTAppDelegate import ReactAppDependencyProvider import UIKit @main class AppDelegate: RCTAppDelegate { var rootView: UIView?; static var shared: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { self.moduleName = "appName" self.dependencyProvider = RCTAppDependencyProvider() self.initialProps = [:] self.rootView = self.createRootView( with: RCTBridge( delegate: self, launchOptions: launchOptions ), moduleName: self.moduleName!, initProps: self.initialProps! ); return super.application(application, didFinishLaunchingWithOptions: launchOptions) } override func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { if (connectingSceneSession.role == UISceneSession.Role.carTemplateApplication) { let scene = UISceneConfiguration(name: "CarPlay", sessionRole: connectingSceneSession.role) scene.delegateClass = CarSceneDelegate.self return scene } let scene = UISceneConfiguration(name: "Phone", sessionRole: connectingSceneSession.role) scene.delegateClass = PhoneSceneDelegate.self return scene } override func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {} override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } } PhoneSceneDelegate.swift import Foundation import UIKit import SwiftUI class PhoneSceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow?; func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if session.role != .windowApplication { return } guard let appDelegate = (UIApplication.shared.delegate as? AppDelegate) else { return } guard let windowScene = (scene as? UIWindowScene) else { return } let rootViewController = UIViewController() rootViewController.view = appDelegate.rootView; let window = UIWindow(windowScene: windowScene) window.rootViewController = rootViewController self.window = window window.makeKeyAndVisible() } } App.tsx import React, {useEffect, useState} from 'react'; import type {PropsWithChildren} from 'react'; import {CarPlay, ListTemplate} from 'react-native-carplay'; import { ScrollView, StatusBar, StyleSheet, Text, useColorScheme, View, } from 'react-native'; import { Colors, DebugInstructions, Header, LearnMoreLinks, ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; type SectionProps = PropsWithChildren<{ title: string; }>; function Section({children, title}: SectionProps): React.JSX.Element { const isDarkMode = useColorScheme() === 'dark'; return ( <View style={styles.sectionContainer}> <Text style={[ styles.sectionTitle, { color: isDarkMode ? Colors.white : Colors.black, }, ]}> {title} </Text> <Text style={[ styles.sectionDescription, { color: isDarkMode ? Colors.light : Colors.dark, }, ]}> {children} </Text> </View> ); } function App(): any { // React.JSX.Element const isDarkMode = useColorScheme() === 'dark'; const backgroundStyle = { backgroundColor: isDarkMode ? Colors.darker : Colors.lighter, }; const [carPlayConnected, setCarPlayConnected] = useState(CarPlay.connected); useEffect(() => { function onConnect() { setCarPlayConnected(true); CarPlay.setRootTemplate(new ListTemplate(/** This renders fine on the CarPlay side */)); } function onDisconnect() { setCarPlayConnected(false); } CarPlay.registerOnConnect(onConnect); CarPlay.registerOnDisconnect(onDisconnect); return () => { CarPlay.unregisterOnConnect(onConnect); CarPlay.unregisterOnDisconnect(onDisconnect); }; }); if (carPlayConnected) { console.log('car play connected'); } else { console.log('car play not connected'); } const safePadding = '5%'; // This doesn't render on the phone? return ( <View style={backgroundStyle}> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} backgroundColor={backgroundStyle.backgroundColor} /> <ScrollView style={backgroundStyle}> <View style={{paddingRight: safePadding}}> <Header/> </View> <View style={{ backgroundColor: isDarkMode ? Colors.black : Colors.white, paddingHorizontal: safePadding, paddingBottom: safePadding, }}> <Section title="Step One"> Edit <Text style={styles.highlight}>App.tsx</Text> to change this screen and then come back to see your edits. </Section> <Section title="See Your Changes"> <ReloadInstructions /> </Section> <Section title="Debug"> <DebugInstructions /> </Section> <Section title="Learn More"> Read the docs to discover what to do next: </Section> <LearnMoreLinks /> </View> </ScrollView> </View> ); } const styles = StyleSheet.create({ sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', }, highlight: { fontWeight: '700', }, }); export default App; I have been attempting to get this working now for some 20+ hours with no luck with searching for answers elsewhere. I am very new to building apps with React Native and Swift so could do with some support.
0
0
325
Mar ’25
MacOS Scale to view
on iOS you can choose to scale to view to have the app resize the screen easily in the developer environment. Scale to view is however not easily done on MacOS using NS to solve on MacOS now. Is it possible for the Apple developer team to make this easier for the Developer, as I understand it is for iOS applications?
0
0
261
Feb ’25
SwiftUI Gestures prevent subview gesture when build with XCode 16 in iOS 18
I have a view with some buttons, and add 2 gestures using simultaneously. My app works well when built with XCode less than 16, or run on iOS less than 18.0. Example code is below: VStack(spacing: 0) { Button { print("button tapped") } label: { Rectangle() .foregroundColor(.red) } .frame(height: 100) } .gesture( DragGesture(minimumDistance: 0) .onEnded { value in print("single tap") } .simultaneously(with: TapGesture(count: 2).onEnded { print("double tap") } ) ) .frame(width: 200, height: 200) .border(Color.purple) I expect the action on Button should be recognized and print out button tapped, but only single tap and double tap are recognized
0
1
339
Mar ’25
How to Visualize Data in a DataFrame Using Charts
I want to visualize the data stored in a DataFrame using various charts (barmark, sectormark, linemark, etc.). My questions are as follows: Can a DataFrame be used directly within a chart? If so, could you provide a simple example? If it cannot be used directly, what is the correct way to use it? Could you provide an example? Thank you for your help. Best regards.
0
1
388
Jan ’25
SwiftUI @Observable Causes Extra Initializations When Using Reference Type Properties
I've encountered an issue where using @Observable in SwiftUI causes extra initializations and deinitializations when a reference type is included as a property inside a struct. Specifically, when I include a reference type (a simple class Empty {}) inside a struct (Test), DetailsViewModel is initialized and deinitialized twice instead of once. If I remove the reference type, the behavior is correct. This issue does not occur when using @StateObject instead of @Observable. Additionally, I've submitted a feedback report: FB16631081. Steps to Reproduce Run the provided SwiftUI sample code (tested on iOS 18.2 & iOS 18.3 using Xcode 16.2). Observe the console logs when navigating to DetailsView. Comment out var empty = Empty() in the Test struct. Run again and compare console logs. Change @Observable in DetailsViewModel to @StateObject and observe that the issue no longer occurs. Expected Behavior The DetailsViewModel should initialize once and deinitialize once, regardless of whether Test contains a reference type. Actual Behavior With var empty = Empty() present, DetailsViewModel initializes and deinitializes twice. However, if the reference type is removed, or when using @StateObject, the behavior is correct (one initialization, one deinitialization). Code Sample import SwiftUI enum Route { case details } @MainActor @Observable final class NavigationManager { var path = NavigationPath() } struct ContentView: View { @State private var navigationManager = NavigationManager() var body: some View { NavigationStack(path: $navigationManager.path) { HomeView() .environment(navigationManager) } } } final class Empty { } struct Test { var empty = Empty() // Comment this out to make it work } struct HomeView: View { private let test = Test() @Environment(NavigationManager.self) private var navigationManager var body: some View { Form { Button("Go To Details View") { navigationManager.path.append(Route.details) } } .navigationTitle("Home View") .navigationDestination(for: Route.self) { route in switch route { case .details: DetailsView() .environment(navigationManager) } } } } @MainActor @Observable final class DetailsViewModel { var fullScreenItem: Item? init() { print("DetailsViewModel Init") } deinit { print("DetailsViewModel Deinit") } } struct Item: Identifiable { let id = UUID() let value: Int } struct DetailsView: View { @State private var viewModel = DetailsViewModel() @Environment(NavigationManager.self) private var navigationManager var body: some View { ZStack { Color.green Button("Show Full Screen Cover") { viewModel.fullScreenItem = .init(value: 4) } } .navigationTitle("Details View") .fullScreenCover(item: $viewModel.fullScreenItem) { item in NavigationStack { FullScreenView(item: item) .navigationTitle("Full Screen Item: \(item.value)") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { withAnimation(completionCriteria: .logicallyComplete) { viewModel.fullScreenItem = nil } completion: { var transaction = Transaction() transaction.disablesAnimations = true withTransaction(transaction) { navigationManager.path.removeLast() } } } } } } } } } struct FullScreenView: View { @Environment(\.dismiss) var dismiss let item: Item var body: some View { ZStack { Color.red Text("Full Screen View \(item.value)") .navigationTitle("Full Screen View") } } } Console Output With var empty = Empty() in Test DetailsViewModel Init DetailsViewModel Init DetailsViewModel Deinit DetailsViewModel Deinit Without var empty = Empty() in Test DetailsViewModel Init DetailsViewModel Deinit Using @StateObject Instead of @Observable DetailsViewModel Init DetailsViewModel Deinit Additional Notes This issue occurs only when using @Observable. Switching to @StateObject prevents it. This behavior suggests a possible issue with how SwiftUI handles reference-type properties inside structs when using @Observable. Using a struct-only approach (removing Empty class) avoids the issue, but that’s not always a practical solution. Questions for Discussion Is this expected behavior with @Observable? Could this be an unintended side effect of SwiftUI’s state management? Are there any recommended workarounds apart from switching to @StateObject? Would love to hear if anyone else has run into this or if Apple has provided any guidance!
0
0
328
Feb ’25
@State memory leak Xcode 16.2
Hi, A class initialized as the initial value of an @State property is not released until the whole View disappears. Every subsequent instance deinitializes properly. Am I missing something, or is this a known issue? struct ContentView: View { // 1 - init first SimpleClass instance @State var simpleClass: SimpleClass? = SimpleClass(name: "First") var body: some View { VStack { Text("Hello, world!") } .task { try? await Task.sleep(for: .seconds(2)) // 2 - init second SimpleClass instance and set as new @State // "First" should deinit simpleClass = SimpleClass(name: "Second") // 3 - "Second" deinit just fine simpleClass = nil } } } class SimpleClass { let name: String init(name: String) { print("init: \(name)") self.name = name } deinit { print("deinit: \(name)") } } output: init: First init: Second deinit: Second Thanks
0
0
271
Feb ’25
Occasional PDFKit crash at PageLayout::getWordRange(unsigned long, long)
At this line of code (SketchTextSelectionManager.swift:449), sometimes there will be crashes based on crashlytics reports. let selection = pdfPage.selectionForWord(at: location) This is directly calling into PDFKit's PDFPage#selection method: https://developer.apple.com/documentation/pdfkit/pdfpage/selectionforword(at:) Attached the full stacktrace: Crashed: com.apple.root.user-initiated-qos.cooperative 0 CoreGraphics 0x30c968 PageLayout::getWordRange(unsigned long, long) const + 908 1 CoreGraphics 0x30bbc0 PageLayout::getTextRangeIndex(CGPoint, CGPDFSelectionType, SelectionPrecision) const + 2292 2 CoreGraphics 0x44a53c CGPDFSelectionCreateBetweenPointsWithOptions + 384 3 PDFKit 0x8d5f8 -[PDFPage selectionFromPoint:toPoint:type:] + 168 4 PDFKit 0x92040 -[PDFPage _rvItemAtPoint:] + 64 5 PDFKit 0x91f4c -[PDFPage rvItemAtPoint:] + 84 6 PDFKit 0x8caa8 -[PDFPage selectionForWordAtPoint:] + 40 7 MyApp 0x8420e0 closure #1 in SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 449 (SketchTextSelectionManager.swift:449) 8 MyApp 0x841a70 SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 205 (CurrentNoteManager.swift:205) 9 libswift_Concurrency.dylib 0x61104 swift::runJobInEstablishedExecutorContext(swift::Job*) + 252 10 libswift_Concurrency.dylib 0x63a28 (anonymous namespace)::ProcessOutOfLineJob::process(swift::Job*) + 480 11 libswift_Concurrency.dylib 0x611c4 swift::runJobInEstablishedExecutorContext(swift::Job*) + 444 12 libswift_Concurrency.dylib 0x62514 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 144 13 libdispatch.dylib 0x15d8c _dispatch_root_queue_drain + 392 14 libdispatch.dylib 0x16590 _dispatch_worker_thread2 + 156 15 libsystem_pthread.dylib 0x4c40 _pthread_wqthread + 228 16 libsystem_pthread.dylib 0x1488 start_wqthread + 8 ```
0
1
297
Feb ’25
iPhone mirroring and controlling
One of my clients is interested in developing a system similar to BrowserStack for internal team usage. Could you please guide me on how to approach the development of this system? Specifically, the project requires: Full iPhone screen recording. Capturing and executing click events on the iPhone. Do I need to obtain permission from Apple for these functionalities?
0
0
367
Jan ’25
XCode breakpoint possible for "Publishing changes from within view updates is not allowed, this will cause undefined behavior."?
Dear Sirs, I'm searching for the most straightforward way to identify the root of a "Publishing changes from within view updates is not allowed, this will cause undefined behavior." warning. It is a complex SwiftUI project and I think there should be a better way than just try and error with disabling/removing and enabling/adding different screen elements to check if the warning still is shown. I tried to set a symbolic breakpoint for "os_log" in my XCode project and indeed this is triggered right before the warning appears but the callstack doesn't give me a direct hint to the part of my code which causes this warning. What would be the most direct way and is there something like an exception handler in such cases? Thanks and best regards, Johannes
0
0
472
Jan ’25
Detect change to apps Screen Time Access
I'm creating an app which gamifies Screen Time reduction. I'm running into an issue with apples Screen Time setting where the user can disable my apps "Screen Time access" and get around losing the game. Is there a way to detect when this setting is disabled for my app? I've tried using AuthorizationCenter.shared.authorizationStatus but this didn't do the trick. Does anyone have an ideas?
0
0
405
Feb ’25
Using AsyncStream vs @Observable macro in SwiftUI (AVCam Sample Code)
I want to understand the utility of using AsyncStream when iOS 17 introduced @Observable macro where we can directly observe changes in the value of any variable in the model(& observation tracking can happen even outside SwiftUI view). So if I am observing a continuous stream of values, such as download progress of a file using AsyncStream in a SwiftUI view, the same can be observed in the same SwiftUI view using onChange(of:initial) of download progress (stored as a property in model object). I am looking for benefits, drawbacks, & limitations of both approaches. Specifically, my question is with regards to AVCam sample code by Apple where they observe few states as follows. This is done in CameraModel class which is attached to SwiftUI view. // MARK: - Internal state observations // Set up camera's state observations. private func observeState() { Task { // Await new thumbnails that the media library generates when saving a file. for await thumbnail in mediaLibrary.thumbnails.compactMap({ $0 }) { self.thumbnail = thumbnail } } Task { // Await new capture activity values from the capture service. for await activity in await captureService.$captureActivity.values { if activity.willCapture { // Flash the screen to indicate capture is starting. flashScreen() } else { // Forward the activity to the UI. captureActivity = activity } } } Task { // Await updates to the capabilities that the capture service advertises. for await capabilities in await captureService.$captureCapabilities.values { isHDRVideoSupported = capabilities.isHDRSupported cameraState.isVideoHDRSupported = capabilities.isHDRSupported } } Task { // Await updates to a person's interaction with the Camera Control HUD. for await isShowingFullscreenControls in await captureService.$isShowingFullscreenControls.values { withAnimation { // Prefer showing a minimized UI when capture controls enter a fullscreen appearance. prefersMinimizedUI = isShowingFullscreenControls } } } } If we see the structure CaptureCapabilities, it is a small structure with two Bool members. These changes could have been directly observed by a SwiftUI view. I wonder if there is a specific advantage or reason to use AsyncStream here & continuously iterate over changes in a for loop. /// A structure that represents the capture capabilities of `CaptureService` in /// its current configuration. struct CaptureCapabilities { let isLivePhotoCaptureSupported: Bool let isHDRSupported: Bool init(isLivePhotoCaptureSupported: Bool = false, isHDRSupported: Bool = false) { self.isLivePhotoCaptureSupported = isLivePhotoCaptureSupported self.isHDRSupported = isHDRSupported } static let unknown = CaptureCapabilities() }
0
0
376
Dec ’24
SFSafariViewController's preferred colors are invalidated after rotation
There are two issues about SFSafariViewController. After rotate from landscape to portrait, The topAnchor is destroyed. The specified bar tint color and control tint color are invalidated.(Returns to system color) Regarding the second issue, I’ve found a temporary workaround. Override the viewWillTransition(to:with:) and keep it empty. Don't call super.viewWillTransition(to:with:). Since UIKit is not open source, I don’t know the exact cause, but I found something that could be the key to the issue. So, I reported it to Apple Feedback Assistant. You can check the details and the sample project in the GitHub repository below. https://github.com/ueunli/SafariViewer
0
0
302
Feb ’25
Publishing changes from within view updates is not allowed - SwiftUI with ARKit
Hello, I’m encountering the error "Publishing changes from within view updates is not allowed, this will cause undefined behavior". while developing an app using SwiftUI and ARKit. I have a ObjectTracking class where I update some @Published variables inside a function called processObjectAttributes after detecting objects. However, when I try to update these state variables in the View (like isPositionChecked, etc.), the error keeps appearing. Here is a simplified version of my code: class ObjectTracking: ObservableObject { @Published var isPositionChecked: Bool = false @Published var isSizeChecked: Bool = false @Published var isOrientationChecked: Bool = false func checkAttributes(objectAnchor: ARObjectAnchor, _ left: ARObjectAnchor.AttributeLocation, _ right: ARObjectAnchor.AttributeLocation? = nil, threshold: Float) -> Bool { let attributes = objectAnchor.attributes guard let leftValue = attributes[left]?.floatValue else { return false } let rightValue = right != nil ? attributes[right!]?.floatValue ?? 0 : 0 return leftValue > threshold && (right == nil || rightValue > threshold) } func isComplete(objectAnchor: ARObjectAnchor) -> Bool { isPositionChecked = checkAttributes(objectAnchor: objectAnchor, .positionLeft, .positionRight, threshold: 0.5) isSizeChecked = checkAttributes(objectAnchor: objectAnchor, .sizeLeft, .sizeRight, threshold: 0.3) isOrientationChecked = checkAttributes(objectAnchor: objectAnchor, .orientationLeft, .orientationRight, threshold: 0.3) return isPositionChecked && isSizeChecked && isOrientationChecked } func processObjectAttributes(objectAnchor: ARObjectAnchor) { currentObjectAnchor = objectAnchor } } In my View, I am using @ObservedObject to observe the state of these variables, but the error persists when I try to update them during view rendering. Could anyone help me understand why this error occurs and how to avoid it? I understand that state should not be updated during view rendering, but I can’t find a solution that works in this case. Thank you in advance for your help!
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
336
Jan ’25
SwiftUI infinite rendering loop when using a custom Binding to a dictionary-based store
I’m building a SwiftUI app where the struct AppGroup is identified by a UUID and stored in a dictionary. My Task model has appGroupId: UUID?. In TaskDetailView, I create a custom Binding<AppGroup> from the store, then navigate to AppGroupDetailView. However, when I tap the NavigationLink, the console spams logs, CPU hits 100%, and it never stabilizes. Relevant Code AppGroupStore (simplified) class AppGroupStore: ObservableObject { @Published var appGroupsDict: [UUID: AppGroup] = [:] func updateAppGroup(_ id: UUID, appGroup: AppGroup) { appGroupsDict[id] = appGroup } // Returns a binding so views can directly read/write the AppGroup by id func getBinding(withId id: UUID?) -> Binding<AppGroup> { Binding( get: { if let id = id { return self.appGroupsDict[id] ?? .empty } return .empty }, set: { newValue in print("New value set for \(newValue.name)") self.updateAppGroup(newValue.id, appGroup: newValue) } ) } // ... } AppGroup is a simple struct: struct AppGroup: Identifiable, Codable { let id: UUID var name: String var apps: [String] static let empty = AppGroup(id: UUID(), name: "Empty", apps: []) } TaskDetailView (main part) struct TaskDetailView: View { @Binding var task: ToDoTask // has task.appGroupId: UUID? @EnvironmentObject var appGroupStore: AppGroupStore var body: some View { let appGroup = appGroupStore.getBinding(withId: task.appGroupId) print("Task load") // prints infinitely, CPU 100% return List { // ... NavigationLink(destination: AppGroupDetailView(appGroup: appGroup)) { Text(appGroup.wrappedValue.name) } } .navigationTitle(task.name) } } AppGroupDetailView (simplified) struct AppGroupDetailView: View { @Binding var appGroup: AppGroup // ... var body: some View { List { ForEach(appGroup.apps, id: \.self) { app in Text(app) } } .navigationTitle(appGroup.name) } } Symptoms: Tapping the NavigationLink leads to infinite “Task load” logs and 100% CPU usage. The set closure (“New value set for...”) is never called, so it’s not repeatedly writing. If I replace the Binding<AppGroup> with a read-only approach (just accessing the dictionary), it does not get stuck. Question: What might cause SwiftUI to keep re-rendering the body indefinitely, even if my custom get closure doesn’t explicitly mutate the state? Are there known pitfalls when using a dictionary-based store and returning a Binding like this? Any help is much appreciated! Thanks in advance for your insights!
0
0
239
Jan ’25
Custom slider png on gui
Im student, hobbyst on developing. i have a problem inserting a custom slidee PNG to control volume of an áudio file in an app. The slidee built in Swift, runs ok. When i try to use a custom png it show in the Gui but when move its button right it disappear beyond the maximum but when i move ir left the minimamente is at middle of the slider scale
Topic: UI Frameworks SubTopic: SwiftUI
0
0
39
Apr ’25
UITabBarController y psoition issue for iOS 18
I am trying to give bottom padding to tabbar i.e ** tabBarFrame.origin.y = view.frame.height - tabBarHeight - 30** but it is not moving up from bottom, it gets sticked to bottom = 0 and the tabbar content moving up taher than tabbar itself.. Code snippet is - `i override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let tabBarHeight: CGFloat = 70 // Custom height for the capsule tab bar var tabBarFrame = tabBar.frame tabBarFrame.size.height = tabBarHeight tabBarFrame.size.width = view.frame.width - 40 tabBarFrame.origin.y = view.frame.height - tabBarHeight - 30 tabBarFrame.origin.x = 20 tabBar.frame = tabBarFrame tabBar.layer.cornerRadius = tabBarHeight / 2 tabBar.clipsToBounds = true view.bringSubviewToFront(tabBar) }` Can anyone please help to resolve the issue for iOS 18, it is coming in iOS 18 rest previous versions are fine with the code.
0
0
327
Jan ’25