Hi.
I know to know which window gets hardware keyboard events (such as shortcut key) currently on iPad.
Until iPadOS 15.0, UIApplication.shared.keyWindow, which was deprecated on iPadOS 13.0 and didBecomeKeyNotification/didResignKeyNotification.
But after iPadOS 15.0, a keyWindow is managed by UIScene, not by UIApplication.
Each scene of my app always has just one window.
For my purpose, checking deprecated UIApplication.shared.keyWindow is still effective but didBecomeKeyNotification and didResignKeyNotification don't work because they are fired when a change happens only inside the scene.
So my questions are,
What is the new alternative of UIApplication.shared.keyWindow?
I know a wrong hack like
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first?.windows.filter { $0.isKeyWindow }.first
does not work since the order of connectedScenes is not related with getting hardware keyboard events.
What are the new alternatives of didBecomeKeyNotification/didResignKeyNotification which work on inter-scene?
The second question is more crucial.
Because about the first question, I can still use deprecated UIApplication.shared.keyWindow.
Thanks.
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.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi all,
I am developing an app that scans barcodes using VisionKit, but I am facing some difficulties.
The accuracy level is not at where I hope it to be at. Changing the “qualityLevel” parameter from balanced to accurate made the barcode reading slightly better, but it is still misreading some cases. I previously implemented the same barcode scanning app with AVFoundation, and that had much better accuracy. I tested it out, and barcodes that were read correctly with AVFoundation were read incorrectly with VisionKit . Is there anyway to improve the accuracy of the barcode reading in VisionKit? Or is this something that is built in and the developer cannot change? Either way, any ideas on how to improve reading accuracy would help.
Thanks in advance!
I currently face an Issue where the SafeAreaInsets on the iPhone 16 Pro Max is not respected on LaunchScreens.
Lets say you have an ImageView whose leading, trailing and top are equal to the SafeAreaLayoutGuides leading, trailing and top.
Then you have a SwiftUI View such as the following representing the same layout in code:
GeometryReader { reader in
ZStack {
VStack(spacing: 0) {
Spacer(minLength: 0)
.frame(height: reader.safeAreaInsets.top)
Image(decorative: "splashLogo")
Spacer(minLength: 0)
}
.frame(width: reader.size.width)
}
.edgesIgnoringSafeArea(.all)
}
Both the storyboard preview as well as the SwiftUI preview show identical results in Xcode. Launching the app on the device however briefly shows the image below the Dynamic Island cutout until the app is launched to the SwiftUI view. Noticed this only happening on the iPhone 16 Pro Max.
Topic:
UI Frameworks
SubTopic:
General
I've encountered what appears to be a bug with widget background image tinting in SwiftUI. When using an image in containerBackground(for: .widget) to fill the entire widget, adding the .containerBackgroundRemovable(false) modifier breaks the widget's tinting behavior:
The background image becomes permanently tinted, ignoring any widgetAccentedRenderingMode(_ renderingMode: WidgetAccentedRenderingMode?) settings
Text elements become tinted even with .widgetAccentable(false) applied
Sample code:
struct MyWidget: Widget {
var body: some WidgetConfiguration {
AppIntentConfiguration(kind: "MyWidget", intent: MyWidgetIntent.self, provider: Provider()) { entry in
MyWidgetView(entry: entry)
.containerBackground(for: .widget) {
Image("background")
.resizable()
.widgetAccentedRenderingMode(.fullColor)
.scaledToFill()
}
}
.containerBackgroundRemovable(false) // This causes the issue
}
}
Workaround: I've managed to resolve this by using a ZStack with disabled content margins and passing the widget size through the entry. However, this seems like unintended behavior with the .containerBackgroundRemovable(false) modifier.
Has anyone else encountered this issue or found a better solution?
Device: iPhone 15 Pro
iOS Version: 18.1
Xcode Version: 16.1
I’m currently working on a SwiftUI project and trying to implement a transition effect similar to ZoomTransitions. However, I’ve run into an issue.
When transitioning from Page A to Page B using .navigationTransition(.zoom(sourceID: "world", in: animation)), Page A shrinks as expected, but its background color changes to the default white instead of the color I preset.
I want the background color of Page A to remain consistent with my preset during the entire transition process. Here’s a simplified version of my code:
Page A
PartnerCard()
.matchedTransitionSource(id: item.id, in: animation)
Page B
``.navigationTransition(.zoom(sourceID: "world", in: animation))
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello, everyone!
I'm currently working on creating tests for a study project in Swift. My current task is to create a test to check if a file is saved correctly.
The workflow in the app is as follows:
Launch the app.
Open a file within the app.
Modify the file.
Save it inside the app.
Save it to the Files app.
I need to verify if the saved file in the Files app is identical to a base file stored in the app bundle.
Initially, I thought I could solve this by creating a UI test, which I've already implemented up to a certain point. The UI test successfully navigates through the workflow steps until it's time to compare the saved file with the base file.
The problem is that I cannot open a saved file from the Files app in a UI test because it operates in a sandboxed environment and cannot interact with external app scopes.
So, my question is: What should I do in this case?
Would it be better to create a unit test specifically for testing the save function and ensure the UI test only verifies if the expected filename exists in the Files app?
I would prefer an end-to-end (E2E) test that covers the entire workflow, but it seems Swift splits tests into Unit and UI test groups, making this approach less straightforward.
Any suggestions or best practices would be greatly appreciated!
The aim is to save the data of a program in 2 different formats of choice, say type1 (default) and type2.
No problem when + (BOOL)autosavesInPlace is NO, you can save as… and get a choice.
No problem when + (BOOL)autosavesInPlace is YES and you created a new document, you can choose when saving.
But you do not get a choice when you created the new file by duplicating a existing file. It takes the type of the latter.
(Using dataOfType:error:, but did not find a solution either by using writeToURL:ofType:error:, duplicateDocument:, etc.)
Topic:
UI Frameworks
SubTopic:
AppKit
Noticed in iOS 18 that List element with animation modifier behaves differently. Seems that on first change of the underlying State property List updates all elements and loses its scroll position even if you insert just one element.
The following code reproduces the behaviour, if you run it on iOS 17 it will behave as expected, you'll see an element being added to the list with an acompanying animation. On iOS 18 you'll lose your scroll position and judging by the animation it seems to update all the other rows in the list even though only one element of the underlaying State property was inserted. After that first update, list element on iOS will behave as expected.
To reproduce the issue scroll down to the ~50th element and tap on a row, compare the behaviour on iOS 17 and iOS 18.
import SwiftUI
struct ContentView: View {
struct ViewState: Equatable {
struct Value: Identifiable, Equatable {
let id: String
var text: String
var value: Bool
}
let list: [Value]
}
@State var viewState: [ViewState.Value] = {
return (0..<100).map { id in
ViewState.Value(
id: "\(id)",
text: "Row number: \(id + 1)",
value: Bool.random()
)
}}()
var body: some View {
list(viewState)
}
@ViewBuilder
private func list(_ list: [ViewState.Value]) -> some View {
List {
ForEach(list) { row in
self.value(row)
}
}
.animation(.default, value: viewState)
}
@ViewBuilder
private func value(_ value: ViewState.Value) -> some View {
Button(action: {
guard let rowIndex = viewState.firstIndex(where: { $0.id == value.id }) else {
return
}
viewState.insert(randomValue(id: rowIndex), at: rowIndex + 1)
}) {
VStack {
Text(value.text)
Text("\(value.value ? "ON" : "OFF")")
.foregroundStyle(value.value ? Color.green : Color.red)
}
}
}
private func randomValue(id: Int) -> ContentView.ViewState.Value {
let id = (id*100 + 1)
return .init(id: "New id: \(id)", text: "Row number: \(id)", value: Bool.random())
}
}
Issues has already been reported using feedback assistant FB16082730
Anyone know how to reduce the padding between list section header (plain style) and search bar? I have tried all available method on google but none work. The default list style does not have this big padding/space between the section header and the search bar.
struct Demo: View {
@State private var searchText: String = ""
var body: some View {
NavigationStack {
List {
Section {
ForEach(0..<100) { index in
Text("Sample value for \(index)")
}
} header: {
Text("Header")
.font(.headline)
}
}
.listStyle(.plain)
.navigationTitle("Demo")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $searchText)
}
}
}
Hi,
I'm experiencing a layout issue in SwiftUI when using TabView, NavigationStack, and a List in a specific navigation flow. Here's how to reproduce it:
Tap on Tab 3.
Tap "Tap Me to go to the subview" to navigate to the detail view.
In the detail view, tap Back to return to Tab 3.
Tap "Tap Me to go to the subview" again.
Problem: When returning to the detail view, the content (especially the List) appears incorrectly positioned within the safe area, as if it's overlapping or misaligned with the navigation bar. This happens only when navigating back and forth after dismissing a sheet presented from a different tab.
This animated gif shows the workflow to visualize the problem:
Expected Behavior: The content should consistently respect the safe area and be positioned correctly under the navigation bar.
Thanks in advance for your help!
Here is the complete code to reproduce the issue:
import SwiftUI
@Observable
class MenuSelector {
var initialIndex: Int
var customTabIndex: Int
var isCustomTabSelected: Bool = false
private var previousIndex: Int
init(customTabIndex: Int, initialIndex: Int = 0) {
self.initialIndex = initialIndex
self.customTabIndex = customTabIndex
self.itemSelected = initialIndex
self.previousIndex = initialIndex
}
var itemSelected: Int {
didSet {
if itemSelected == customTabIndex {
previousIndex = oldValue
itemSelected = oldValue
isCustomTabSelected = true
}
}
}
}
struct NavigationStackSpikeView: View {
@State private var tabSelector = MenuSelector(customTabIndex: 1)
var body: some View {
TabView(selection: $tabSelector.itemSelected) {
Text("Tab 1")
.tabItem {
Text("Tab 1")
}
.tag(0)
Text("I want to present a sheet for this tab")
.tabItem {
Text("Action")
}
.tag(1)
Tab3View()
.tabItem {
Text("Tab 3")
}
.tag(2)
}
.sheet(isPresented: $tabSelector.isCustomTabSelected) {
SheetView()
}
}
}
struct Tab3View: View {
@State private var navigationPath = NavigationPath()
var body: some View {
NavigationStack(path: $navigationPath) {
VStack {
NavigationLink(value: Destination.subview) {
Text("Tap Me to go to the subview")
}
}
.navigationDestination(for: Destination.self) { destination in
switch destination {
case .subview:
DetailView()
}
}
}
}
enum Destination: Hashable {
case subview
}
}
struct DetailView: View {
var body: some View {
VStack {
List {
Text("A detail")
}
.listStyle(.plain)
}
.navigationTitle("Details")
.navigationBarTitleDisplayMode(.inline)
}
}
struct SheetView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Text("I'm a sheet")
Button("Dismiss") { dismiss() }
}
}
}
#Preview {
NavigationStackSpikeView()
}
May I inquire about the differences between the two ways of view under the hood in SwiftUI?
class MyViewModel: ObservableObject {
@Published var state: Any
init(state: Any) {
self.state = state
}
}
struct MyView: View {
@StateObject var viewModel: MyViewModel
var body: some View {
// ...
}
}
struct CustomView: View {
let navigationPath: NavigationPath
@StateObject var viewModel: MyViewModel
var body: some View {
Button("Go to My View") {
navigationPath.append(makeMyView())
}
}
}
// Option 1: A viewModel is initialized outside view's initialization
func makeMyView(state: Any) -> some View {
let viewModel = MyViewModel(state: state)
MyView(viewModel: viewModel)
}
// Option 2: A viewModel is initialized inside view's initialization
func makeMyView(state: Any) -> some View {
MyView(viewModel: MyViewModel(state: state))
}
For option 1, the view model will be initialized whenever custom view is re-rendered by changes whereas the view model is only initialized once when the view is re-rendered for option 2.
So what happens here?
Dear Experts,
I created a SwiftUI View (in a UIKit based project) whose objective is to display a short animation in the front of the user screen. I developed it 8 month ago in XCode 15 for iOS 17, no problems.
But since iOS 18, I can observe huge lags on my animation only in Release app. The problem is not present in Debug app.
I don't understand why this problem occurs, the animation is quite simple, it's just an offset deplacement.
I tried many thing like:
Show the animation with a UINavigationController
Show the animation with a UIWindow
Move the view with .position
Remove the GeometryReader
All other animation
withAnimation and .animation
Task and DispatchQueue
Etc...
I found that the laggy animation occurs when I set the Optimization Level for the Swift Compiler - Code Generation to Optimize for Speed [-O]. That's very strange because we had this option on Release for iOS 17 and we had no lags...
I can share to you a Sample Repository with the configuration we have. https://github.com/Thibma/sample-animation-swiftui
Today the only option I used is to develop this feature in UIKit but it's too bad to skip the SwiftUI opportunity. :/
If you have any ideas to resolve this, I take !
Thank you !
We're encountering a UX challenge with the automatic App Store notification banner that appears when users first launch our App Clips (not the App Clip sheet). This notification, which suggests downloading the full app, is creating confusion among our users. We've observed that some users tap the notification instead of completing their intended action within the App Clip, interrupting their workflow.
Is there a way to disable this banner?
This crash occurs when the app is started, and it is not necessary. The probability of occurrence is relatively low and it is not easy to reproduce. Please guide me how to deal with it. Thank you
Please see the crash log below
Crash log
I have a simple SwiftUI Text:
Text(t) .font(Font.system(size: 9))
Strangely its ideal height seems to be larger when it is empty.
I initially observed this in a custom Layout container that wasn't working quite right. Eventually I looked at the height returned by v.dimensions(in:), and found that when t is non-empty the height is 11; when empty, it's 14.
Subsequently I observed similar behaviour in a regular VStack container.
Has anyone seen anything similar? Are there any properties that could affect this behaviour?
(This is on a watch - I don't know if that matters.)
Hi all,
Is there way to check the status of multi-stage text input in the TextField of SwiftUI?
I am essentially trying to detect if the user is entering some text with multi-stage text input method right now. (e.g., Japanese, Chinese, etc).
TextField("Search", text: $searchText)
.onKeyPress(keys: [.upArrow, .downArrow]) { event in
if ....some condition here... {
// ignore up/down keys when multi-stage input
return .ignored
}
else {
// do some special key handling
// when multi-stage input is not running
return .handled
}
}
Multi-stage text input uses up/down keys to choose words from candidates, so I don't want to handle the keys when it is happening.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello,
I am currently encountering an issue where SwiftUI View Previews cannot be displayed when the View is defined in a Static Framework target. This issue only occurs under specific conditions.
Environment
Xcode: 16.2
Scheme Structure:
MainApp
Test Target: TestHogeFeature
Test Setting:
Gather coverage (Code coverage collection) enabled(all)
Target Structure:
MainApp (Application target)
Dependencies: [HogeFeature, Core]
HogeFeature (Static Framework target)
Dependencies: [Core]
Core (Framework target)
Dependencies: None
TestHogeFeature (Unit test target)
Dependencies: [HogeFeature]
Summary
I am currently working on a SwiftUI-based project and have encountered an issue where Previews fail to display under specific conditions. Below are the details:
Issue
In the MainApp scheme, when the code coverage collection setting (Gather coverage for) is enabled, Previews for SwiftUI Views within the HogeFeature (Static Framework) target fail to display correctly. However, the issue is resolved by taking one of the following actions:
Change HogeFeature from a Static Framework to a Dynamic Framework.
Remove the build setting MACH_O_TYPE: staticlib
Disable the Gather coverage setting in the MainApp scheme.
I have attached the actual error log from the failed Preview.
preview error log
Questions
Why does this issue occur only when using a Static Framework with code coverage enabled?
Is there any way to resolve this issue while maintaining the current configuration (Static Framework with code coverage enabled)?
I would appreciate any advice or insights regarding the cause and potential solutions.
Hi everyone,
I’m working on an iOS app using both UITableViewDiffableDataSource and SwiftUI, and I’m facing two separate but puzzling issues:
UITableViewDiffableDataSource Not Reusing Cells on first applying after initial Snapshot. After applying first time it is working as expected from second time.
SwiftUI View’s inside UITableViewCell onDisappear Not Triggering the on first changes of snapshot after initial snapshot.
With normal UITableView it is working fine.
Issue causing - it is causing player & cells to retain memory extensively
Sample gist code for reproducing with diffable (DiffableTableViewExampleViewController) and working fine without diffable (RegularTableViewExampleViewController)
https://gist.github.com/SURYAKANTSHARMA/d83fa9e7e0de309e27485100ba5aed17
Any insights or suggestions for these issues would be greatly appreciated!
Thanks in advance!
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.
When the APP is in the background, using AccessorySetupKit, calling showPicker is invalid. When I tested it before, it was valid on iOS 18.0, but it is invalid after updating to iOS 18.1.1. Is this a bug? Will it be fixed later?
Topic:
UI Frameworks
SubTopic:
UIKit