Running up Xcode 16.2 Beta 1, a lot of my code that used onPreferenceChange in Views to change @State properties of those views, such as some notion of a measured width is now complaining about mutating the @MainActor-isolated properties from Sendable closures.
Now I've got to hoop-jump to change @State properties from onPreferenceChange? OK, but seems a bit of extra churn.
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
My SwiftUI app uses an Image with a tap gesture:
Image(systemName: "xmark.circle.fill")
.accessibilityIdentifier(kTextFieldClearButton)
.foregroundColor(.secondary)
.padding(.trailing, 6)
.onTapGesture {
dataSource.textFieldText = ""
}
In a UI test, I want to tap this image to execute its action:
let clearButton = app.images[kTextFieldClearButton]
clearButton.tap()
However the action is not executed.
I then set a breakpoint at clearButton.tap(), to execute lldb commands. Here are the results:
(lldb) p clearButton.isHittable
t = 439.54s Find the "TextFieldClearButton" Imag
(Bool) true
e
It is a little strange that "Image" has been interrupted by (Bool) true, but the image is hittable.
p clearButton.isAccessibilityElement
gives
(lldb) p clearButton.isAccessibilityElement
(Bool) false
I don't understand why this Image is no accessibility element. I thought, SwiftUI Views are by default accessible.
What can I do to make it accessible so that clearButton.tap() works as expected?
I am writing to report an issue I encountered with iOS 18 beta that affects my application, which has been available on the App Store for over two years and currently has over 60,000 active users.
My application utilizes a UITabBarController to manage multiple tabs, where each tab hosts a UIViewController embedded within a UINavigationController. The application operates in two different states, where users may have either 5, 4, or 3 tabBarItems depending on their configuration.
The issue arises when fewer than 5 tabs are present. In these cases, I add child view controllers to the UITabBarController to ensure they are displayed above the tab bar, rather than below it. The relevant code snippet is as follows:
tabBarController.addChild(childController)
tabBarController.view.addSubview(childController.view)
Prior to iOS 18, this implementation functioned as expected. However, with the release of iOS 18, adding a child view controller to the UITabBarController results in the child being incorrectly added as a UITabBarItem. This misbehavior leads to an application crash when the unintended tab is selected.
The crash trace is as follows:
"Inconsistency in UITabBar items and view controllers detected. No view controller matches the UITabBarItem '<UITabBarItem: 0x142d9c480> selected'."
I have attached screenshots from iOS 18 and previous versions to illustrate the issue, which compares the expected behavior in earlier iOS versions with the problematic behavior in iOS 18.
I appreciate your attention to this matter and look forward to any guidance or resolution you can provide.
Hi,
the new style of tab bar is at top, sort of a picker style , how to enforce SwiftUI to use it in old style fashion at bottom in iPadOS same as iOS ?
—
Kind Regards
Topic:
UI Frameworks
SubTopic:
SwiftUI
How do I implement the same Navigation split view with a side bar in Appkit?
Basically I have this code:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationSplitView {
// Sidebar
List {
NavigationLink("Item 1", value: "Item 1 Details")
NavigationLink("Item 2", value: "Item 2 Details")
NavigationLink("Item 3", value: "Item 3 Details")
}
.navigationTitle("Items")
} content: {
// Main content (detail view for selected item)
Text("Select an item to see details.")
.padding()
} detail: {
// Detail view (for the selected item)
Text("Select an item from the sidebar to view details.")
.padding()
}
}
}
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
and wanted to somehow convert it to Appkit. I tried to use an NSSplitViewController but I still don't have that side bar and that button to collapse it, how do I go about this?
We've got a hard to repro issue on Intel only when performing UI layout. It seems the collection view code gets into a recursive loop of doom and eventually the app crashes.
This is only happening on Intel, the ARM version is fine. It seems related to this issue: https://developer.apple.com/forums/thread/732580 There an Apple Dev acknowledges that there are issues with the Intel version of the OS.
Here's the simplified stack we're seeing:
-[NSISEngine _coreReplaceMarker:withMarkerPlusDelta:]"
-[NSISEngine constraintDidChangeSuchThatMarker:shouldBeReplacedByMarkerPlusDelta:]",
-[NSISEngine tryToChangeConstraintSuchThatMarker:isReplacedByMarkerPlusDelta:undoHandler:]",
-[NSLayoutConstraint _tryToChangeContainerGeometryWithUndoHandler:]",
-[NSLayoutConstraint _setSymbolicConstant:constant:symbolicConstantMultiplier:]",
-[NSLayoutConstraint setConstant:]",
-[NSView(NSConstraintBasedLayoutInternal) _updateSimpleAutoresizingConstraintsInPlace:forAutoresizingMask:]",
NSViewUpdateConstraintsForFrameChange
-[NSView setFrameSize:]",
-[NSView setFrame:]",
-[NSClipView _updateOverhangSubviewsIfNeeded]",
-[NSClipView _reflectDocumentViewFrameChange]",
-[NSView _postFrameChangeNotification]","
-[NSView setFrameSize:]",
-[NSCollectionView setFrameSize:]",
-[NSView setFrame:]",
NSViewActuallyUpdateFrameFromLayoutEngine",
-[NSView resizeSubviewsWithOldSize:]",
-[NSView setFrameSize:]",
-[NSClipView setFrameSize:]",
-[NSView setFrame:]",
-[NSScrollView _setContentViewFrame:]",
-[NSScrollView tile]",
-[NSScrollView _tileWithoutRecursing]",
-[NSScrollView reflectScrolledClipView:]",
-[NSClipView _reflectDocumentViewFrameChange]_block_invoke",
-[NSClipView _reflectDocumentViewFrameChange]",
-[NSView _postFrameChangeNotification]",
-[NSView setFrameSize:]",
-[NSCollectionView setFrameSize:]",
-[NSView setFrame:]",
-[NSCollectionView _resizeToFitContentAndClipView]",
-[_NSCollectionViewCore setContentSize:]",
-[_NSCollectionViewCore _updateVisibleCellsNow:]"
-[_NSCollectionViewCore _updateVisibleCellsNow:]"
-[_NSCollectionViewCore _updateVisibleCellsNow:]"
-[_NSCollectionViewCore _updateVisibleCellsNow:]"
.
.
It seems to be limited to macOS 13.1 too. Hoping someone might have a clue?
Thanks,
Robert.
Here's a link to the full stack: https://www.icloud.com/notes/076h1RXj4rvv7TzS5ICnvG6vw#NSCollectionView_crash_stack:
Topic:
UI Frameworks
SubTopic:
AppKit
Hello, I am having the following issue:
I am using the packages DSWaveformImage and DSWaveformImageViews if that matters. My code's goal is to generate waveform images from files embedded in the application. That works great on a simulator device, but when I run the code on a physical device (iPhone 15 Pro, iOS 18.2), I get this error (shown in the attached screenshot below):
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello. Recently, while studying alignmentGuide, I had questions about it behaving differently from the documentation when setting multiple alignment guides.
For example, the document states that only the alignmentGuide modifier with a first parameter matching the container's alignment will function.
Therefore, I thought that writing the Swift code below would result in the yellow color's center alignment being aligned with the HStack's bottom alignment.
struct TestView: View {
var body: some View {
HStack(alignment: .bottom) {
Color.yellow
.frame(height: 50)
.alignmentGuide(VerticalAlignment.center) { dim in
dim[.top]
}
.alignmentGuide(VerticalAlignment.top) { dim in
dim[.bottom]
}
.alignmentGuide(VerticalAlignment.bottom) { dim in
dim[VerticalAlignment.center]
}
Text("Hello, world")
}
.border(.green)
}
}
Expect
However, in reality, I observed that the top of the yellow color aligns with the HStack's bottom alignment. From this, I inferred that the 3rd alignmentGuide is applied first, and this also causes the first alignmentGuide to work, which makes me curious about how this is possible. If I leave only the 3rd alignmentGuide, it behaves as I expected.
Real Behavior
Could anybody help me to figure it out this behavior? Thank you
I have a UITableView which contains a UICollectionView in the first row. It used to work fine in iOS17, but now I get a crash when running with Xcode 16 / iOS18 beta:
Expected dequeued view to be returned to the collection view in preparation for display. When the collection view's data source is asked to provide a view for a given index path, ensure that a single view is dequeued and returned to the collection view. Avoid dequeuing views without a request from the collection view. For retrieving an existing view in the collection view, use -[UICollectionView cellForItemAtIndexPath:] or -[UICollectionView supplementaryViewForElementKind:atIndexPath:]
This is my UITableView delegate call:
AddEditDataCell *cell = nil;
if (indexPath.section == 0) {
if (indexPath.row == 0) {
AddEditDataContactsCell *contactNameCell = (AddEditDataContactsCell *)[self cellForContactNamesCollectionAtIndexPath:indexPath tableView:tableView];
return contactNameCell;
- (AddEditDataContactsCell *)cellForContactNamesCollectionAtIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
AddEditDataContactsCell *contactsCell = (AddEditDataContactsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"ContactsCell" forIndexPath:indexPath];
if (self.collectionNameCell == nil) {
self.collectionNameCell = [contactsCell.collectionView dequeueReusableCellWithReuseIdentifier:@"LogContactNameCollectionCellIdentifier" forIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
contactsCell.nameCellDelegate = self;
}
contactsCell.frame = CGRectZero;
[contactsCell setNeedsLayout];
[contactsCell.collectionView reloadData];
contactsCell.collectionViewHeightConstraint.constant = contactsCell.collectionView.collectionViewLayout.collectionViewContentSize.height;
[contactsCell.collectionView.collectionViewLayout invalidateLayout];
return contactsCell;
}
Topic:
UI Frameworks
SubTopic:
UIKit
I'm starting with the template code from Apple from:
File > New Project > macOS app using Swift UI and Swift Data. Selection works fine if only adding items, but after deleting any selected item selection stops working for some rows. It seems like the UI and model get out of sync. After restarting the app, or simply launching a new window, it works again. Is this a known bug in Swift UI and is there a workaround?
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
.onDelete(perform: deleteItems)
}
.navigationSplitViewColumnWidth(min: 180, ideal: 200)
.toolbar {
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
I am working on Agora Voice Call and using CallKit to manage incoming and outgoing calls.
Issue:
When I accept a call, CallKit goes behind my app. I want CallKit to remain in front of my app. Please guide me.
As can be seen in the screenshot attached, I can not see the options in this window. A prompt window before this also did not show any buttons in the visible space. However, I made a guess and could get to this window by clicking on what I think was "Ok" or something similar.
But on this I could not do any action and had to force quit the app.
Getting these two warnings:
Could not find or use auto-linked framework 'CoreAudioTypes': framework 'CoreAudioTypes' not found
Could not parse or use implicit file '/Applications/Xcode16.0/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore.tbd': cannot link directly with 'SwiftUICore' because product being built is not an allowed client of it
Followed by 100 + errors like below
Undefined symbol: _TIFFCleanup & Undefined symbol: _TIFFReadRGBAImageOriented .....
Any ideas? I have tried adding CoreAudioTypes etc. Error is not clear. Am trying to stop using Rosetta
Topic:
UI Frameworks
SubTopic:
General
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)
}
}
On a ScrollView+LazyVStack, the addition of .scrollTargetLayout causes many list items to be initialized, instead of the ordinary economical behavior of LazyVStack, where only the necessary items and views are initialized. Even worse, as the stack is scrolled down, all list items are reinitialized for every small scroll.
Without, .scrollTargetLayout, everything works fine.
I've tried every variation of locating modifiers, and different ways of identifying the list items, with no success.
Any ideas? Thanks.
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Post.created, ascending: true)],
animation: .default)
private var posts: FetchedResults<Post>
var body: some View {
ZStack{
ScrollView{
LazyVStack(spacing:0) {
ForEach(posts, id: \.self) { post in
PostView(post: post)
}
.onDelete(perform: deletePosts)
}.scrollTargetLayout() // <---- causes multiple Posts re-instantiations for any small scroll, very slow
}
.scrollPosition(id: $scrolledID)
.scrollTargetBehavior(.paging)
When my iOS app runs on macOS in "designed for iPad" mode, the system foreground colour RGBA values seem strange.
Looking at [UIColor labelColor], [UIColor secondaryLabelColor] etc. on iOS, I see values like these: (Light Mode)
// R G B A
fg0 = 0 0 0 255
fg1 = 10 10 13 153
fg2 = 10 10 13 76
fg3 = 10 10 13 45
Note in particular that fg0, aka labelColor, is solid black.
When I run it on my Mac, the values I see are:
// R G B A
fg0 = 0 0 0 216
fg1 = 0 0 0 127
fg2 = 0 0 0 66
fg3 = 0 0 0 25
Here, fg0 has alpha = 216.
The result is that it looks like a dark grey, on a white background.
Of course it's reasonable for macOS to have a different colour palette than iOS - but native macOS apps seem to have solid 100% black as their foreground colour.
Do others see this? What should I be doing?
Note that I'm getting colour values using UIColor's getRed: blue: green: alpha: method and then using these colour values for some custom GPU drawing. Previously I was using solid black and white, but at some point I updated it to use UIColor in order to respond to light/dark-mode changes.
I want to use Objective C language to implement a button, click the button to achieve the function of Menu Bar - Full Screen Tile - Left of Screen. What should I do? I couldn't find the relevant API.
Topic:
UI Frameworks
SubTopic:
AppKit
Hi,
I have the following swiftUI code:
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.colorEffect(ShaderLibrary.AlphaConvert())
and the following shader:
[[ stitchable ]] half4 AlphaConvert(float2 position, half4 currentColor) {
return half4(currentColor.r>0.5,currentColor.r<=0.5,0,(currentColor.r>0.5));
}
I am loading a full-res image from my photo library (24MP)... The image initially displays fine, with portions of the image red, and the rest black (due to alpha blending)... However, after rotating the device, I get an image that is a combination of red&green... Note, that the green pixels from the shader have alpha 0, hence, should never be seen. Is there something special that needs to be done on orientation changes so that the shader works fine?
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.
When I use the following code
List {
ForEach(data.items, id: \.knowledgeInfo.mediaID) { item in
SelectableKnowledgeListItem(knowledgeData: item, baseID: data.knowledgeBaseID, isSelectionMode: $isSelectionMode, selectedItems: $selectedItems)
.KnowledgeListItemStyle()
}
// 添加底部加载更多
if !data.isEnd && !isRefreshing {
ProgressView()
.frame(maxWidth: .infinity, alignment: .center)
.onAppear {
self.isRefreshing = true
manager.getKnowledgeList(knowledgeBaseID: data.knowledgeBaseID, completion: {
self.isRefreshing = false
})
}
}
}
.animation(.interactiveSpring)
.scrollContentBackground(.hidden)
.environment(\.defaultMinListHeaderHeight, 7)
The number of Views rendered in the List remains unchanged after he adds an item to data.items (data is an ObservedObject, items is Published) at runtime.When I removed .animation(.interactiveSpring), it would be processed normally.And if I perform a delete operation after adding, it will cause a crash.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the collection view after the update (11) must be equal to the number of sections contained in the collection view before the update (10), plus or minus the number of sections inserted or deleted (1 inserted, 1 deleted).
Topic:
UI Frameworks
SubTopic:
SwiftUI