I want to get the availableInputs list in widgetextension, but it always returns only the phone's microphone. I have confirmed that I have connected additional Bluetooth devices. Why is this?
If I want to get the information I want, how should I do it?
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Post
Replies
Boosts
Views
Activity
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)
We've seen an issue when using a LazyVGrid inside a List. The app crashes with:
Thread 1: Fatal error: <UpdateCoalescingCollectionView 0x600000ca0d20> is stuck in a recursive layout loop
When debugging the issue, we were able to narrow down the issue to a minimum reproducible example below:
struct ContentView: View {
let columns = [
GridItem(.adaptive(minimum: 43))
]
var body: some View {
List {
LazyVGrid(columns: columns) {
ForEach(0..<15) { value in
if value == 0 {
Text("a")
} else {
Color.clear
}
}
}
}
}
}
The issue can be reproduced on iPhone 15 Pro Max and iOS 18.x specifically.
In a production app we have a similar layout, but instead of GridItem(.adaptive) we use GridItem(.flexible).
Hi! I'm attempting to run the Quakes Sample App^1 from macOS. I am running breakpoints and confirming the mapCameraKeyframeAnimator is being called:
.mapCameraKeyframeAnimator(trigger: selectedId) { initialCamera in
let start = initialCamera.centerCoordinate
let end = quakes[selectedId]?.location.coordinate ?? start
let travelDistance = start.distance(to: end)
let duration = max(min(travelDistance / 30, 5), 1)
let finalAltitude = travelDistance > 20 ? 3_000_000 : min(initialCamera.distance, 3_000_000)
let middleAltitude = finalAltitude * max(min(travelDistance / 5, 1.5), 1)
KeyframeTrack(\MapCamera.centerCoordinate) {
CubicKeyframe(end, duration: duration)
}
KeyframeTrack(\MapCamera.distance) {
CubicKeyframe(middleAltitude, duration: duration / 2)
CubicKeyframe(finalAltitude, duration: duration / 2)
}
}
But I don't actually see any map animations taking place when that selection changes.
Running the application from iPhone simulator does show the animations.
I am building from Xcode Version 16.2 and macOS 15.2. Are there known issues with this API on macOS?
Hello!
I want to programmatically set the editMode in SwiftUI for a view as soon as it appears. However, I have read a lot now but it only works via the EditButton - but not programmatically. I'm using the simulator for this example and Xcode Version 15.4.
struct EditTodos: View {
@State private var editMode = EditMode.inactive
@State var content = ["apple", "banana", "peanut"]
var body: some View {
NavigationStack {
List {
ForEach(content, id: \.self) { item in
Text(item)
}
.onDelete { _ in }
.onMove { _, _ in }
}
.onAppear {
editMode = .active // note: not working, why??
}
.navigationBarItems(
trailing: HStack(spacing: 20) {
EditButton()
}
)
}
}
}
#Preview {
EditTodos()
}
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?
Try the following code on macOS, and you'll see the marker is added in the wrong place, as the conversion from screen coordinates to map coordinates doesn't work correctly.
The screenCoord value is correct, but reader.convert(screenCoord, from: .local) offsets the resulting coordinate by the height of the content above the map, despite the .local parameter.
struct TestMapView: View {
@State var placeAPin = false
@State var pinLocation :CLLocationCoordinate2D? = nil
@State private var cameraProsition: MapCameraPosition = .camera(
MapCamera(
centerCoordinate: .denver,
distance: 3729,
heading: 92,
pitch: 70
)
)
var body: some View {
VStack {
Text("This is a bug demo.")
Text("If there are other views above the map, the MapProxy doesn't convert the coordinates correctly.")
MapReader { reader in
Map(
position: $cameraProsition,
interactionModes: .all
)
{
if let pl = pinLocation {
Marker("(\(pl.latitude), \(pl.longitude))", coordinate: pl)
}
}
.onTapGesture(perform: { screenCoord in
pinLocation = reader.convert(screenCoord, from: .local)
placeAPin = false
if let pinLocation {
print("tap: screen \(screenCoord), location \(pinLocation)")
}
})
.mapControls{
MapCompass()
MapScaleView()
MapPitchToggle()
}
.mapStyle(.standard(elevation: .automatic))
}
}
}
}
extension CLLocationCoordinate2D {
static var denver = CLLocationCoordinate2D(latitude: 39.742043, longitude: -104.991531)
}
(FB13135770)
This is my code in ContentView:
import SwiftUI
import SceneKit
import PlaygroundSupport
struct ContentView: View {
var body: some View {
VStack {
Text("SceneKit with SwiftUI")
.font(.headline)
.padding()
SceneView(
scene: loadScene(),
options: [.autoenablesDefaultLighting, .allowsCameraControl]
)
.frame(width: 400, height: 400)
.border(Color.gray, width: 1)
}
}
}
func loadScene() -> SCNScene? {
if let fileURL = Bundle.main.url(forResource: "a", withExtension: "dae") {
do {
let scene = try SCNScene(url: fileURL, options: [
SCNSceneSource.LoadingOption.checkConsistency: true
])
print("Scene loaded successfully.")
return scene
} catch {
print("Error loading scene: \(error.localizedDescription)")
}
} else {
print("Error: Unable to locate a.dae in Resources.")
}
return nil
}
a.dae file exists in the Resources section of macOS Playground app. And a.dae can be viewed in Xcode.
Console shows: Error loading scene: The operation couldn’t be completed. (Foundation._GenericObjCError error 0.)
Any input is appreciated.
I am trying out the new TextField selection ability on macOS but it crashes in various different ways with extremely large stack traces. Looks like it is getting into re-entrant function calls.
A similar problem is described on the SwiftUI forums with no responses yet.
Here is my simple example
struct ContentView: View {
@State private var text: String = ""
@State private var selection: TextSelection?
var body: some View {
TextField("Message", text: $text, selection: $selection)
.padding()
}
}
Setting text to a value like "Hallo World" causes an instant crash as soon as you start typing in the TextField.
Setting text empty (as in example above) lets you edit the text but as it crashes as soon as you commit it (press enter).
Any workarounds or fixes?
I recently started exploring the latest version of SwiftUI and encountered an issue while working with TabView and NavigationStack. I downloaded the example code provided by Apple and began making changes to explore new SwiftUI features. However, I noticed that the navigation bar "jumps" or resets when switching between tabs, even in their example implementation.
Here are some changes which I made below in the files:
LibraryView:
.navigationTitle("Library")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(Color("AccentColor"),for: .navigationBar)
WatchNowView:
.navigationTitle("Watch Now")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(Color("AccentColor"),for: .navigationBar)
example code url :- destinationVideo
I suspect the issue arises because each tab bar item has its own NavigationStack. When we set a navigation title for each view, the NavigationStack resets the navigation bar on view appearance, which causes this visual bug.
Thank you!
I recently started exploring the latest version of SwiftUI and came across a issue while working with TabView and NavigationStack. I downloaded Apple’s provided example code and began making changes to explore new SwiftUI changes. i added navigationtitle and toolbarBackground to first two tab. However, I noticed that the navigation bar "jumps" or resets when switching between tabs, even in their own example implementation.
Here’s a simplified version of the example code I was testing:
file name - WatchNowView
.navigationTitle("Watch Now")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(Color("AccentColor"),for: .navigationBar)
file name - LibraryView
.navigationTitle("Library")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(Color("AccentColor"),for: .navigationBar)
Here is a sample code link (provided by Apple developer document) : destination-video
I have attached a gif below demonstrating this issue:
Questions:
Is this behavior expected in the latest version of SwiftUI, or is it a bug in the framework's handling of TabView and NavigationStack?
Is this behavior expected as all tabbar item have their own nativationStack?
Are there any official recommendations for maintaining seamless navigation experiences when using navigationStack and TabView?
This behavior detracts from the otherwise smooth experience SwiftUI aims to provide. If anyone has encountered this issue and found a workaround, I’d greatly appreciate your insights. I hope Apple can review this problem to enhance the usability of SwiftUI. Thank you!
I am currently developing my submission for the SSC and I noticed that the swift playgrounds app for iOS does not have support for the new swift ui features in iOS 18. Are we allowed to submit apps that use these iOS 18 only features?
Recently I noticed how my ViewModels aren't deallocating and they end up as a memory leaks. I found something similar in this thread but this is also happening without using @Observation. Check the source code below:
class CellViewModel: Identifiable {
let id = UUID()
var color: Color = Color.red
init() { print("init") }
deinit { print("deinit") }
}
struct CellView: View {
let viewModel: CellViewModel
var body: some View {
ZStack {
Color(viewModel.color)
Text(viewModel.id.uuidString)
}
}
}
@main
struct LeakApp: App {
@State var list = [CellViewModel]()
var body: some Scene {
WindowGroup {
Button("Add") {
list.append(CellViewModel())
}
Button("Remove") {
list = list.dropLast()
}
ScrollView {
LazyVStack {
ForEach(list) { model in
CellView(viewModel: model)
}
}
}
}
}
}
When I tap the Add button twice in the console I will see "init" message twice. So far so good. But then I click the Remove button twice and I don't see any "deinit" messages.
I used the Debug Memory Graph in Xcode and it showed me that two CellViewModel objects are in the memory and they are owned by the CellView and some other objects that I don't know where are they coming from (I assume from SwiftUI internally).
I tried using VStack instead of LazyVStack and that did worked a bit better but still not 100% "deinits" were in the Console.
I tried using weak var
struct CellView: View {
weak var viewModel: CellViewModel?
....
}
but this also helped only partially.
The only way to fully fix this is to have a separate class that holds the list of items and to use weak var viewModel: CellViewModel?. Something like this:
class CellViewModel: Identifiable {
let id = UUID()
var color: Color = Color.red
init() { print("init") }
deinit { print("deinit") }
}
struct CellView: View {
var viewModel: CellViewModel?
var body: some View {
ZStack {
if let viewModel = viewModel {
Color(viewModel.color)
Text(viewModel.id.uuidString)
}
}
}
}
@Observable
class ListViewModel {
var list = [CellViewModel]()
func insert() {
list.append(CellViewModel())
}
func drop() {
list = list.dropLast()
}
}
@main
struct LeakApp: App {
@State var viewModel = ListViewModel()
var body: some Scene {
WindowGroup {
Button("Add") {
viewModel.insert()
}
Button("Remove") {
viewModel.drop()
}
ScrollView {
LazyVStack {
ForEach(viewModel.list) { model in
CellView(viewModel: model)
}
}
}
}
}
}
But this won't work if I want to use @Bindable such as
@Bindable var viewModel: CellViewModel?
I don't understand why SwiftUI doesn't want to release the objects?
Xcode 14.1
Running on iPhone 14 Pro max simulator 16.1
Code...
import SwiftUI
struct ContentView: View {
@State var loggedIn: Bool = false
var body: some View {
switch loggedIn {
case false:
Button("Login") {
loggedIn = true
}
.onAppear {
print("🍏 Login on appear")
}
.onDisappear {
print("🍎 Login on disappear")
}
case true:
TabView {
NavigationView {
Text("Home")
.navigationBarTitle("Home")
.onAppear {
print("🍏 Home on appear")
}
.onDisappear {
print("🍎 Home on disappear")
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Logout") {
loggedIn = false
}
}
}
}
.tabItem {
Image(systemName: "house")
Text("Home")
}
NavigationView {
Text("Savings")
.navigationBarTitle("Savings")
.onAppear {
print("🍏 Savings on appear")
}
.onDisappear {
print("🍎 Savings on disappear")
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Logout") {
loggedIn = false
}
}
}
}
.tabItem {
Image(systemName: "dollarsign.circle")
Text("Savings")
}
NavigationView {
Text("Profile")
.navigationBarTitle("Profile")
.onAppear {
print("🍏 Profile on appear")
}
.onDisappear {
print("🍎 Profile on disappear")
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Logout") {
loggedIn = false
}
}
}
}
.tabItem {
Image(systemName: "person")
Text("Profile")
}
}
.onAppear {
print("🍏 Tabview on appear")
}
.onDisappear {
print("🍎 Tabview on disappear")
}
}
}
}
Video of bug... https://youtu.be/oLKjRGL2lX0
Example steps...
Launch app
Tap Login
Tap Savings tab
Tap Home tab
Tap Logout
Expected Logs...
🍏 Login on appear
🍏 Tabview on appear
🍏 Home on appear
🍎 Login on disappear
🍏 Savings on appear
🍎 Home on disappear
🍏 Home on appear
🍎 Savings on disappear
🍏 Login on appear
🍎 Home on disappear
🍎 Tabview on disappear
Actual logs...
🍏 Login on appear
🍏 Tabview on appear
🍏 Home on appear
🍎 Login on disappear
🍏 Savings on appear
🍎 Home on disappear
🍏 Home on appear
🍎 Savings on disappear
🍏 Login on appear
🍏 Savings on appear
🍎 Home on disappear
🍎 Savings on disappear
🍎 Tabview on disappear
Error...
10 and 12 in the actual logs should not be there at all.
For each tab that you have visited (that is not the current tab) it will call onAppear and onDisappear for it when the tab view is removed.
Hello,
In my app, I have an onboarding made of multiple steps in a NavigationStack.
I also have a state variable that controls an if else root branch to show either the onboarding NavigationStack or the app content if the onboarding is finished.
I noticed that when I end the onboarding (i.e. I switch to the other part of the if else root branch), the onAppear of the first View in the NavigationStack of the onboarding is called again. I don’t understand why.
Is this a bug?
Thanks,
Axel
enum Step {
case one
case two
case three
case four
}
struct ContentView: View {
@State private var isFinished: Bool = false
@State private var steps: [Step] = []
var body: some View {
if isFinished {
Button("Restart") {
steps = []
isFinished = false
}
} else {
NavigationStack(path: $steps) {
VStack {
Text("Start")
.onAppear { print("onAppear: start") }
Button("Go to step 1") { steps.append(.one) }
}
.navigationDestination(for: Step.self) { step in
switch step {
case .one:
Button("Go to step 2") { steps.append(.two) }
.onAppear { print("onAppear: step 1") }
case .two:
Button("Go to step 3") { steps.append(.three) }
.onAppear { print("onAppear: step 2") }
case .three:
Button("Go to step 4") { steps.append(.four) }
.onAppear { print("onAppear: step 3") }
case .four:
Button("End") {
isFinished = true
}
.onAppear { print("onAppear: end") }
}
}
}
.onAppear { print("onAppear: NavigationStack") }
}
}
}
When running a Mac Catalyst app that uses DocumentGroup, the app fails to display the document content. The document picker works as expected, but creating a new document or opening an existing one results in an empty window. This issue occurs regardless of whether “Optimize for Mac” or “Scale iPad” is selected.
Steps to Reproduce:
1. Download the sample project provided by Apple for building a document-based app in SwiftUI.
2. Delete the macOS version of the project.
3. Add a Mac Catalyst version of the app.
4. In the Mac Catalyst settings, select “Optimize for Mac” (the bug also appears if it is “Scale iPad”).
5. Run the project on macOS.
Expected Result:
The app should correctly display the content of the document when creating or opening it.
Actual Result:
The app opens an empty window when a new document is created or an existing one is opened.
Impact:
We have received multiple 1-star reviews, and our retention has dropped by two-thirds due to this issue.
Environment: Xcode 16.1; macOS 15.1 & 15.2 (on 15.0 it works fine)
Has anyone experienced the same issue? I filed multiple reports so far.
On iOS you can create a new Lock Screen that contains a bunch of emoji, and they'll get put on the screen in a repeating pattern, like this:
When you have two or more emoji they're placed in alternating patterns, like this:
How do I write something like that? I need to handle up to three emoji, and I need the canvas as large as the device's screen, and it needs to be saved as an image. Thanks!
(I've already written an emojiToImage() extension on String, but it just plonks one massive emoji in the middle of an image, so I'm doing something wrong there.)
Ok… I'm baffled here… this is very strange.
Here is a SwiftUI app:
import SwiftUI
@main struct StepperDemoApp: App {
func onIncrement() {
print(#function)
}
func onDecrement() {
print(#function)
}
var body: some Scene {
WindowGroup {
Stepper {
Text("Stepper")
} onIncrement: {
self.onIncrement()
} onDecrement: {
self.onDecrement()
}
}
}
}
When I run in the app in macOS (Xcode 16.0 (16A242) and macOS 14.6.1 (23G93)), I see some weird behavior from these buttons. My experiment is tapping + + + - - -. Here is what I see printed:
onIncrement()
onIncrement()
onIncrement()
onIncrement()
onDecrement()
What I expected was:
onIncrement()
onIncrement()
onIncrement()
onDecrement()
onDecrement()
onDecrement()
Why is an extra onIncrement being called? And why is one onDecrement dropping on the floor?
Deploying the app to iPhone Simulator does not repro this behavior (I see the six "correct" logs from iPhone Simulator).
I had write a widget after iOS 17+, It had a Toggle to perform a appintent .
When switch the toggle, the appintent will perfrom , just like
`
func perfrom() async throws -> some IntentResult {
// first
let first = try await getFristValue()
let second = try await getSecondValue(by: first)
let third = try awiat getThirdValue(by: second)
return .result()
}
`
and I found, it will work when I am debugging connect with Xcode.
But, when I don't connect xcode, it will not work.
How can I fixed it ?
Before I updated to iOS 18 everything worked fine. I pushed out an update to my application on the App Store and I had no issues. After updating to the latest OS many of my touch events are no longer working and I have no idea why.
Sometimes when the app runs the touch events work fine and other times I can't click on half of my views & buttons. I am completely lost as to what might be happening.
I am having issues all over the application but let's focus on the navigation stack and the toolbar item buttons. I will post some code snippets, I have been unable to replicate this in a small playground project. This is my setup, I have two buttons but lets focus on the home & notifications view.
The custom Router
import SwiftUI
import Foundation
@Observable
class HomeRouter {
var navPath = NavigationPath()
@MainActor
func navigate(to destination: HOME_ROUTES) {
navPath.append(destination)
}
@MainActor
func navigateBack() {
navPath.removeLast()
}
@MainActor
func navigateToRoot() {
navPath.removeLast(navPath.count)
}
}
Home View
import os
import SwiftUI
import CoreLocation
import NotificationCenter
struct Home: View {
@State public var router: HomeRouter
@State private var showDetail = false
@State private var showMoreFields = false
@EnvironmentObject private var session: SessionStore
private var log = Logger(subsystem: "com.olympsis.client", category: "home_view")
init(router: HomeRouter = HomeRouter()) {
self._router = State(initialValue: router)
}
var body: some View {
NavigationStack(path: $router.navPath) {
ScrollView(.vertical) {
//MARK: - Welcome message
WelcomeCard()
.padding(.top, 25)
.environmentObject(session)
// MARK: - Announcements
AnnouncementsView()
.environmentObject(session)
// MARK: - Next Events
NextEvents()
.environmentObject(session)
// MARK: - Hot Events
HotEvents()
.environmentObject(session)
// MARK: - Nearby Venues
NearbyVenues()
.environmentObject(session)
Spacer(minLength: 100)
}
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Text("Olympsis")
.italic()
.font(.largeTitle)
.fontWeight(.black)
}
ToolbarItemGroup(placement: .topBarTrailing) {
Button(action: { router.navigate(to: .messages) }) {
ZStack(alignment: .topTrailing) {
Image(systemName: "bubble.left.and.bubble.right")
.foregroundStyle(Color.foreground)
if session.invitations.count > 0 {
NotificationCountView(value: $session.invitations.count)
}
}
}
Button(action: { router.navigate(to: .notifications) }) {
ZStack(alignment: .topTrailing) {
Image(systemName: "bell")
.foregroundStyle(Color.foreground)
if session.invitations.count > 0 {
NotificationCountView(value: $session.invitations.count)
}
}
}
}
}
.background(Color("background-color/primary"))
.navigationDestination(for: HOME_ROUTES.self, destination: { route in
switch route {
case .notifications:
NotificationsView()
.id(HOME_ROUTES.notifications)
.environment(router)
.environmentObject(session)
.navigationBarBackButtonHidden()
case .messages:
HomeMessagesView()
.id(HOME_ROUTES.messages)
.environment(router)
.environmentObject(session)
.navigationBarBackButtonHidden()
case .full_post_view(let id):
AsyncPostView(postId: id)
.id(HOME_ROUTES.full_post_view(id))
.environmentObject(session)
.navigationBarBackButtonHidden()
}
})
}
}
}
#Preview {
Home()
.environmentObject(SessionStore())
}
The Notifications View
import SwiftUI
struct NotificationsView: View {
@State private var notifications: [NotificationModel] = []
@Environment(HomeRouter.self) private var router
@EnvironmentObject private var session: SessionStore
var body: some View {
ScrollView {
if notifications.count > 0 {
ForEach(notifications, id: \.id){ note in
NotificationModelView(notification: note)
}
} else {
VStack {
Text("No new notifications")
HStack {
Spacer()
}
}.padding(.top, 50)
}
}
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button(action:{ router.navigateBack() }) {
Image(systemName: "chevron.left")
.foregroundStyle(Color.foreground)
}
}
ToolbarItem(placement: .principal) {
Text("Notifications")
}
}
.task {
notifications = session.invitations.map({ i in
NotificationModel(id: UUID().uuidString, type: "invitation", invite: i, body: "")
})
}
}
}
#Preview {
NavigationStack {
NotificationsView()
.environment(HomeRouter())
.environmentObject(SessionStore())
}
}