Its important to note that this same app did not have this issue in iOS 17.
Ever since iOS 18 I have noticed that when application written in SwiftUI uses Label with the default color (which auto changes between light and dark appearance), from time to time when resuming an application that has been in the background, the color of those labels (only the Label elements) switches from the opposite to the correct one. Here is an example:
Steps to reproduce
Phone is in dark appearance
Open app
Labels text color is white and labels background is black
Go to home so that app is on background
Wait random time (does not happen all the time), some times 1 min some times 10
Reopen the application.
During the opening transition the Label text color was changed while the app was in suspended mode to the light appearance variant (black)
Once the app opening transition finishes the Label text color switches back to the correct color for dark appearance (white)
Same issue happens if you start from light appearance. I cannot reproduce this on Xcode simulators, I have tried to force memory warning to check if that has anything to do with it but that also does not cause the issue to appear on simulators. For now I can only reproduce this on real device.
Screenshots
Here is screenshots of the above example:
During transition
After transition
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.
Post
Replies
Boosts
Views
Activity
We are developing an MacOS app from our iOS app using MacCatalyst.
If I press long on the app icon on the Dock, a list of recent files appears.
If I tap one one of these files nothing happens. I would expect the scene delegate function:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)
would be called but it is not. Can somebody maybe explain what I am missing here?
The list of recent files also appears in the Menu under File > Open recent files. There I can tap on a file and it it is opened correctly using the scene delegate method mentioned above.
The files can also be opened with the app using the Finder, so the associated file types with the app are correct.
Hi,
After running the Xcode template "New project > (SwiftUI, SwiftData)" I noticed that there is no insert animation into the list.
The project is a pure vanilla project created from Xcode (Version 16.2 (16C5032a)) and the code is a simple as it gets:
//
// ContentView.swift
//
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)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
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])
}
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
As you see the template's code does have withAnimation inside addItem but there is no animation. The new added item appears without animation in the the List
Here is a short video. Is this a known bug?
0
I am developing a custom Picture in Picture (PiP) app that plays videos. The video continues to play even when the app goes to the background, but I would like to be able to get the bool value when the PiP is hidden on the edge, as shown in the attached image. The reason why we need this is because we don't want the user to consume extra network bandwidth, so we want to pause the video when the PiP is hidden on the edge of the screen. Please let me know if this is possible. This can be done in the foreground or in the background.
Hi all!
Based on documentation: https://developer.apple.com/documentation/carplay/cplistitem/handler
If you need to perform asynchronous tasks, dispatch them to a background queue and call the completion closure or completionBlock when they complete.
In a normal case, it works perfectly. But, if it takes "too much", for example, 10 seconds (streaming with retries, app business logic), when I call the "completionBlock" inside "handler" doesn't do anything.
Exists a timeout in "completionBlock"?
Thanks!
I am developing a custom Picture in Picture (PiP) app that plays videos.
The video continues to play even when the app goes to the background, but I would like to be able to get the bool value when the PiP is hidden on the edge, as shown in the attached image.
The reason why we need this is because we don't want the user to consume extra network bandwidth, so we want to pause the video when the PiP is hidden on the edge of the screen.
Please let me know if this is possible.
This can be done in the foreground or in the background.
I’m experiencing significant performance and memory management issues in my SwiftUI application when displaying a large number of images using LazyVStack within a ScrollView. The application uses Swift Data to manage and display images.
Here’s the model I’m working with:
@Model
final class Item {
var id: UUID = UUID()
var timestamp: Date = Date.now
var photo: Data = Data()
init(photo: Data = Data(), timestamp: Date = Date.now) {
self.photo = photo
self.timestamp = timestamp
}
}
extension Item: Identifiable {}
The photo property is used to store images. However, when querying Item objects using Swift Data in a SwiftUI ScrollView, the app crashes if there are more than 100 images in the database.
Scrolling down through the LazyVStack loads all images into memory leading to the app crashing when memory usage exceeds the device’s limits.
Here’s my view: A LazyVStack inside a ScrollView displays the images.
struct LazyScrollView: View {
@Environment(\.modelContext) private var modelContext
@State private var isShowingPhotosPicker: Bool = false
@State private var selectedItems: [PhotosPickerItem] = []
@Query private var items: [Item]
var body: some View {
NavigationStack {
ScrollView {
LazyVStack {
ForEach(items) { item in
NavigationLink {
Image(uiImage: UIImage(data: item.photo)!)
.resizable()
.scaledToFit()
} label: {
Image(uiImage: UIImage(data: item.photo)!)
.resizable()
.scaledToFit()
}
}
}
}
.navigationTitle("LazyScrollView")
.photosPicker(isPresented: $isShowingPhotosPicker, selection: $selectedItems, maxSelectionCount: 100, matching: .images)
.onChange(of: selectedItems) {
Task {
for item in selectedItems {
if let data = try await item.loadTransferable(type: Data.self) {
let newItem = Item(photo: data)
modelContext.insert(newItem)
}
}
try? modelContext.save()
selectedItems = []
}
}
}
}
}
Based on this:
How can I prevent SwiftUI from loading all the binary data (photo) into memory when the whole view is scrolled until the last item?
Why does SwiftUI not free memory from the images that are not being displayed?
Any insights or suggestions would be greatly appreciated. Thank you!
I will put the full view code in the comments so anyone can test if needed.
According to the MVVM design pattern, one of my views depends on many properties in my model. Can I use logic like @published var model = MyModel()? Will there be a large performance loss? Will the UI be refreshed when other unrelated properties in the model are modified? What is the best practice in this case?
Hello,
I've been using the @Environment(\.dismiss) var dismiss in a SwiftUI app for the last 2 years which means it was working as expected in iOS 16, iOS 17 and for the most part iOS 18 up until iOS 18.2.1 in which it is causing an endless loop and eventually a crash.
It seems to be something about using a the @Environment(\.dismiss) with a NavigationLink which seems to cause this issue.
When I add a log in my swiftUI views with let _ = Self._printChanges(), I see the following printed out in a loop:
CurrentProjectView: _dismiss changed.
SurveyView: @self changed.
Similar issues have been reported:
https://forums.developer.apple.com/forums/thread/720803
https://forums.developer.apple.com/forums/thread/739512
Any idea how to resolve this ?
I want to have my own background and foreground colors for some views and I am having a bit of trouble. I cannot figure out how to remove the margins around some built-in views. One example is below. The ScrollView portion is always black or white, depending on whether I am I dark mode or not. I've added various colors and borders to see what is going on below. I've also tried adding the modifiers to the Scroll View rather than the TextEditor and it doesn't work at all. If I don't have the .frame modifier on the ScrollView, the TextEditor moves to the top of its frame for some reason. I've played with .contentMargins, .edgeInsets, etc. with no luck
How do I get the TextEditor to fill the entire ScrollView without the margin? Thanks!
import SwiftUI
struct TextEditorView: View
{ @Binding var editString: String
var numberOfLines: Int
var lineHeight: CGFloat
{ UIFont.preferredFont(forTextStyle: .body).lineHeight
}
var viewHeight: CGFloat
{ lineHeight * CGFloat(numberOfLines) + 8
}
var body: some View
{ ScrollView([.vertical], showsIndicators: true)
{ TextEditor(text: $editString)
.border(Color.red, width: 5)
.foregroundStyle(.yellow)
.background(.blue)
.frame(minHeight:viewHeight, maxHeight: viewHeight)
.scrollContentBackground(.hidden)
}
.frame(minHeight:viewHeight, maxHeight: viewHeight)
}
}
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 ?
Hi,
Im trying to customize the button that appear when swiping a for each list for deleting trying to show a red circle and a white trash icon inside it, but instead I get a white empty button ?
.swipeActions(edge: .trailing) {
Button {
deletePatient(patient: patient)
} label: {
ZStack {
Circle()
.fill(Color.red)
.frame(width: 50, height: 50)
Image(systemName: "trash")
.foregroundColor(.white)
}
}
.tint(.white)
}
.onReceive construction isn't working with button long press gesture but tap is working, it increases count by 1. Construction should increase count every 0.5 seconds if button pressed
struct Test: View {
@State private var count = 0
@State private var isLongPressed = false
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increase") {
count += 1
print("Button tapped")
}
.onLongPressGesture {
isLongPressed = true
print("Long press started")
}
.onLongPressGesture(minimumDuration: 0) {
isLongPressed = false
print("Long press ended")
}
}
.onReceive(Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()) { _ in
if isLongPressed {
count += 1
print("Count increased: \(count)")
}
}
}
}
Create an Empty visionOS App like this.
starts in windowed mode, when I enter immersive mode and then exit back to windowed mode, I notice that the window appears dimmer. I start a simple project with settings as image shown below, and took screenShots of my window before and after entering immersive space then quit, compare them, the color value did become dimmer. The issue is reliably repeatable in a given room. If this issue is experienced, adjusting the display brightness to the maximum value and then back to the initial setting will restore the colors to the correct state. Force to exit the app then reopen it can do the same restoration.https://drive.google.com/file/d/1m-a4ghNlSkHhAQuvOCF_IAfcdYeJA14j/view?usp=sharing
As per the documentation link, the Tab initializer in SwiftUI should allow supplying a custom view to the Label. However, the colors used within the Label view are not being honored as expected.
I attempted to set custom colors in the Label, but they either default to system-defined styles or are ignored entirely. This behavior does not align with my understanding of how custom views should work in SwiftUI's Label.
Am I missing a step or configuration here, or is this a bug in the current implementation?
struct ContentView: View {
@State private var activeTab: TabItem = .homeTab
var body: some View {
TabView(selection: $activeTab) {
ForEach(TabItem.allCases) { tabItem in
Tab(value: tabItem) {
getView(for: tabItem)
} label: {
VStack(spacing: 0) {
MainTabButtonView(
selected: activeTab == tabItem,
tabItem: tabItem
)
Text(tabItem.title)
}
}
}
}
}
}
private extension ContentView {
@ViewBuilder
func getView(for tabItem: TabItem) -> some View {
switch tabItem {
case .homeTab:
Text("Home")
case .searchTab:
Text("Search")
case .profileTab:
Text("Profile")
case .moreTab:
Text("More")
}
}
}
#Preview {
ContentView()
}
enum TabItem: String, Identifiable, Hashable, CaseIterable {
case homeTab
case searchTab
case profileTab
case moreTab
var tabImage: String {
switch self {
case .homeTab:
"house"
case .searchTab:
"magnifying-glass"
case .profileTab:
"biographic"
case .moreTab:
"hamburger-menu"
}
}
var title: String {
switch self {
case .homeTab:
"Home"
case .searchTab:
"Search"
case .profileTab:
"Profile"
case .moreTab:
"More"
}
}
var id: String {
rawValue
}
}
struct MainTabButtonView: View {
private let selected: Bool
private let tabItem: TabItem
init(
selected: Bool,
tabItem: TabItem
) {
self.selected = selected
self.tabItem = tabItem
}
var body: some View {
Image(tabItem.tabImage)
.renderingMode(.template)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 30, height: 30)
.foregroundStyle(
selected ? Color.green : Color.orange
)
}
}
Expected Behavior:
The custom colors applied within the Label should render as defined.
Actual Behavior:
The colors are overridden or ignored, defaulting to the system-defined styles.
Environment:
Xcode Version: Xcode 16.2
iOS: 18.2
Swift Version: Swift 6
If I show a textfield in my app and set nothing else on it but the following, The keyboard will show an autofill suggestion from a password manager for a one time code.
textField.keyboardType = .numberPad
In this case, the text field is for typing in a count, so iOS suggesting to autofill a one time code is incorrect.
Setting textField.textContentType to nil has no affect on the behaviour.
Prerequisites to reproduce
an app with an associated domain
an entry in a password manager with a one time code for the domain
a textfield with keyboardType set to numberPad
I am implementing a new Intents UI Extension and am noticing that the viewWillDisappear, viewDidDisappear, and deinit methods are not being called on my UIViewController that implements INUIHostedViewControlling, when pressing the "Done" button and dismissing the UIViewController.
This causes the memory for the UI Extension to slowly increase each time I re-run the UI Extension until it reaches the 120MB limit and crashes.
Any ideas as to what's going on here and how to solve this issue?
Worth noting that while the memory does continuously increase on iOS versions before iOS 17, only in 17 and later does the 120MB memory limit kick in and crash the extension.
Having a property inside of an ObservableObject with a type of a closure with a typed throws will crash the app on the initialization of the observable object on iOS 17. Here is an example:
struct ContentView: View {
@StateObject var myDataSource = MyDataSource()
var body: some View {
EmptyView()
}
}
enum MyError: Error {
case error
}
class MyDataSource: ObservableObject {
let signUp: (Int) throws(MyError) -> Void = { _ in }
}
If you run this code on iOS 17, the app will crash. The Radar for this issue is FB16399987.
In macOS, I am encountering an issue where the system API fails to grant permission to open a file despite enabling the necessary Read/Write permissions within the SandBox. Could you please elucidate the reasons behind this behavior? Thanks!
func finderOpenFileSystem(at path: String) {
let fileURL = URL(fileURLWithPath: path)
guard FileManager.default.fileExists(atPath: path) else {
print("Error: File does not exist at path: \(path)")
return
}
let success = NSWorkspace.shared.open(fileURL)
if success {
print("File opened successfully: \(fileURL)")
} else {
print("Error: Failed to open file: \(fileURL)")
}
}
In the fileImporter on iOS, when I select a folder, the result is always a subfile belonging to the private folder. This prevents me from accessing these files within the app. However, I do not wish to store them in the sandbox environment. What steps can I take to resolve this issue?