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.
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Post
Replies
Boosts
Views
Activity
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])
}
}
}
}
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
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):
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
Is it possible to change the default save dialog that appears when creating a document based MacOS app in SwiftUI?
I have a basic FileDocument struct that gets called to a view using a DocumentGroup scene.
struct MyFile: FileDocument {
static let readableContentTypes: [UTType] = [.myFileType]
static let writeableContentTypes: [UTType] = [.myFileType]
var list: [String]
init(configuration: ReadConfiguration) throws {
let data = configuration.file.regularFileContents!
let JSONDecoder = JSONDecoder()
do {
try list = JSONDecoder.decode([String].self, from: data)
} catch {
throw CocoaError(.fileReadCorruptFile)
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let JSONEncoder = JSONEncoder()
JSONEncoder.outputFormatting = .prettyPrinted
do {
data = try JSONEncoder.encode(self.list)
} catch {
print(error.localizedDescription)
throw CocoaError(.fileWriteUnknown)
}
return .init(regularFileWithContents: data)
}
}
This gets called at the DocumentGroup
DocumentGroup(newDocument: MyFile(), editor: { document in
ContentView(document: document.$document)
})
But when I save the file, I want the save dialog that appears to have something like a 'Tags' textField that can also store information about the file.
Something similar to this: (https://i.sstatic.net/AJQ3YNb8.png)
From what I can find, there isn't much information about this other than manually creating an NSSavePanel class and overriding the current save function
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?
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.
I am developing a MacOS app with a vertically oriented ScrollView. Inside that View I use a LazyVStack. In the LazyVStack I have a column of images. I want the images to occupy as much of the LazyVStack width as possible so I created a frame for the VStack with a maxWidth: .infinity.
When the user grabs the edge of the window and drags it to reduce the window width, the Views of the window adjust themselves to fit the reduced space. This includes reducing the width of the images. I maintain a fixed aspect ratio for the images, so the height of the images is reduced too.
My problem arises when the width of the images (and height) reduces to the point where the scroll bar is no longer needed because all of the images fit within the height of the ScrollView, and the ScrollView removes the scroll bar. That triggers a redraw of the images, with a slightly bigger size because the width used by the scroll bar is now available. When the the images get bigger they don't all fit within the height of the ScrollView anymore and the scrollbar is restored. That, of course, reduces the space available for the images, so they are reduced in size again - which then triggers the ScrollView to remove the scrollbar again. The whole thing goes into a spasm of flickering images (bigger and smaller) and scrollbar (off and on) until finally I get the dreaded error message:
The window has been marked as needing another Display Window pass, but it has already had more Display Window passes than there are views in the window.
There seems to be no way to prevent this behavior by setting an option on the ScrollView. It would be great if one could indicate that the scroll bar should always remain visible, or at least that the space occupied by the scroll bar remain, even if it is just empty.
The only way I could solve this problem was to go through a somewhat involved calculation to set the image width in such a way that it still responds to window width changes (and some other size changes I allow in some of the other app's Views). This complication would not be necessary if there were better controls on the scroll bar.
Is there a reason for not providing adequate controls for the ScrollView? Its uncontrollable behavior complicates the programming.
I have a SwiftUI app that needs to be able to receive photos and videos from the Photos app. When the user shares an item from the Photos app they can choose to share to a destination app. When doing so from the Files app, my app appears as a share destination and the .onOpenURL successfully handles the incoming content.
The CFBundleTypeName and CFBundleTypeRole have been configured accordingly. What I don't understand is why I can share from the Files app and select my app as the destination, while not being able to select my app when sharing from the Photos app.
What does the Photos app require to allow a given app to available as a share destination?
I'd also like to be able to do this from other apps such as the YouTube app.
I am trying to create a list of not rectangular elements, each of which has a context menu. However, I am encountering an issue with the corners when performing a long press.
What is the correct way to use such a combination? I don't want to use List because of its default styling. The issue takes place only while animation is in progress.
Here's a simplified code example that can be copied pasted and ran in one file. The video was recorded on the device with iOS 18.2
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { TestView() } }
}
struct TestView: View {
let items = ["Item 1", "Item 2", "Item 3"]
var body: some View {
VStack {
ForEach(items, id: \.self) { item in
HStack {
Text(item)
Spacer()
Image(systemName: "star")
}
.padding()
.background(.yellow)
// tried all these in different combinations, none works
.contentShape(RoundedRectangle(cornerRadius: 10))
.clipShape(RoundedRectangle(cornerRadius: 10))
.containerShape(RoundedRectangle(cornerRadius: 10))
.contextMenu {
Button { print("Edit \(item)") }
label: { Text("Edit"); Image(systemName: "pencil") }
}
}
}
.padding()
}
}
#Preview {
TestView()
}
NavigationTitle does not change when the app language changes. It works well in iOS 17.5 but does not in iOS 18.x
Does anyone have a problem with buttons not clickable in the lists of elements? If I have a list of 30 elements, some of them are clickable and some not. The button is a basic button that prints something in the console. After refresh, click ability is changed but still some clickable and some not. It appears always when compiling with Swift 6. My colleague has the "old" Xcode 15.4 with Swift 5 and when he installs exactly the same code -> buttons and lists work just fine.
I noticed some similar issues with onTapGesture on StackOverflow but my problem is a button. However, I have the same problem with onTapGesture (where I use it) in some of my View components and changing it with highPriorityGesture will not solve the problem since I can't click on the child elements of those Views anymore...
I'm using Xcode 16.2 and iOS 18.2.
Does anyone have an idea how to solve this?
Having written a SwiftUI based app on macOS 15.2 with Xcode 16.2 I built a version for Monterey (which required backing off some modern uses, like #Preview and others). But the SwiftUI layout, positioning and dimensions, didn't use anything new so,
I was surprised that the app did not look exactly the same on Monterey. It was not wildly different, but enough that I had to modify several to frame, padding and font parameters in order to restore my desired appearance.
I'm assuming that over the course of generations of SwiftUI, things change -- that's life, but this was a frustrating process for at least two reasons:
view modifiers can't be conditionally compiled so something like this, for example, isn't possible
RoundedRectangle(cornerRadius: 1)
<if Monterey>
.padding(.horizontal, -2.0)
<else>
.padding(.horizontal, -4.0)
<endif>
.frame(height: 4.0)
previewing views is a challenge. Previewing on Sequoia doesn't show what the views will look like on Monterey. I can build the app on Monterey and use the non-macro #preview mechanism, but in order to do that, and the above, I'm pushed to maintain two versions of my app because the following doesn't compile:
#if swift(>=5.9)
#Preview("Monitor") { MonitorView() }
#else
struct MonitorView_Previews: PreviewProvider {
static var previews: some View {
MonitorView()
}
}
#endif
These are not show-stoppers but I do wonder if I'm missing some mechanism(s) to ease the pain, or if SwiftUI functional changes are documented.
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()
}
Using desaturated mode on an image in a widget will break any links or buttons that use the image as their 'label'.
Using the following will just open the app as if there was no link at all - therefore just using the fallback userActivity handler, or any .widgetURL() urls provided.
Link(destination: URL(string: "bug://never-works")!) {
Image("puppy")
.widgetAccentedRenderingMode(.desaturated)
}
The same goes for buttons:
Button(intent: MyDemoIntent()) {
Image("puppy")
.widgetAccentedRenderingMode(.desaturated)
}
I've tried hacky solutions like putting the link behind the image using a ZStack, and disabling hit testing on the image, but they don't work. Anything else to try?
Logged as Feedback #15152620.
I have an app that I would like to implement sharing an Image from a Button within a .contextMenu as below. I’d like to share from the button in the same way as a ShareLink would.
I see other resources suggest the use of the UIActivityViewController although I was wondering if there is a SwiftUI approach that would not involve UIKit.
.contextMenu {
Button(action: {
debugPrint("Share")
}) {
Label("Share", systemImage: "square.and.arrow.up")
}
}
"the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" ...... it killing me !!!!
I'm trying to achieve a specific UI design in SwiftUI where the bottom section of my List has a different background color than the top section. For example in the Medications portion of the Health app, the "Your Medications" Section has a different background than the top "Log" Section. How do I achieve this?:
Here some example code. I wonder if I am supposed to use two Lists instead. If I use two Lists though and nest it in a ScrollView, the height of the lists needs to be specified. I am working with dynamic content, though so I don't think that is ideal.
class ProtocolMedication {} // Example model
struct HomeView: View {
@Query private var protocolMedications: [ProtocolMedication]
var body: some View {
NavigationStack {
List {
// Upper sections with default background
Section {
Text("Content 1")
} header: {
Text("Log")
}
// Bottom section that needs different background
Section {
ForEach(protocolMedications) { medication in
Text(medication.name)
}
} header: {
Text("Your Medications")
}
}
.listStyle(.insetGrouped)
}
}
}
Suppose there are two buttons in VStack, the second button is unclickable. I'm running macOS 15.2 with Xcode 16.2.
import SwiftUI
struct ContentView: View {
var body: some View {
ScrollView(.horizontal) {
VStack {
Spacer()
// this button is clickable
Button("foo") {
print("foo")
}
// this button can't be clicked
Button("bar") {
print("bar")
}
}
}
}
}
If I change .horizontal -> .vertical and VStack -> HStack, the second button behave normally.
If I remove ScrollView, everything works fine.
it works fine before macOS 15.2.