Hi everyone,
I'm currently facing an issue with AVAudioPlayer in my SwiftUI project. Despite ensuring that the sound file "buttonsound.mp3" is properly added to the project's resources (I dragged and dropped it into Xcode), the application is still unable to locate the file when attempting to play it.
Here's the simplified version of the code I'm using:
import SwiftUI
import AVFoundation
struct ContentView: View {
var body: some View {
VStack {
Button("Play sound") {
playSound(named: "buttonsound", ofType: "mp3")
}
}
}
}
func playSound(named name: String, ofType type: String) {
guard let soundURL = Bundle.main.url(forResource: name, withExtension: type) else {
print("Sound file not found")
return
}
do {
let audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch let error {
print("Error playing sound: \(error.localizedDescription)")
}
}
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
On WWDC25 session "Meet Liquid Glass", two Liquid Glass variants are mentioned: "regular" and "clear". "Regular" seems to be the default setting for UIGlassEffect, but I was not able to find an option for clear.
Is there a native element that uses clear? Is it coming to later betas for iOS 26?
Hi all,
After upgrading to the iOS 26 beta, the scrolling in my SwiftUI chat view is completely broken. The exact same code works perfectly on iOS 18.
Context:
I have a chat view using ScrollViewReader and a vertically-reversed ScrollView (with .rotationEffect(.degrees(180))). Each message row (MessageBubble) uses multiple simultaneousGesture handlers:
Horizontal drag for swipe-to-reply (and other actions: pin, delete)
Long press for showing popover/actions
Vertical scroll for normal chat scrolling
This was working great on iOS 18. In iOS 26 beta, the vertical scroll is either completely disabled, jittery, or hijacked by the message row’s drag gestures, even though .simultaneousGesture is used (see code below).
Minimal Repro Sample
MessageListView.swift
swift
Copy
Edit
ScrollViewReader { proxy in
ScrollView(.vertical, showsIndicators: false) {
LazyVStack(spacing: 0) {
// ... grouped messages
ForEach(...) { ...
MessageBubble(...) // see below
}
Color.clear.frame(height: 8).id("BOTTOM_ANCHOR")
}
.padding(.horizontal, 4)
.rotationEffect(.degrees(180))
}
.rotationEffect(.degrees(180))
}
MessageBubble.swift
struct MessageBubble: View {
// ...
var body: some View {
// horizontal swipe-to-reply gesture
let dragGesture = DragGesture(minimumDistance: 10)
// ...
ZStack {
// ...
HStack { ... }
// ...
.simultaneousGesture(
DragGesture(minimumDistance: 0) // for long press
// ...
)
.simultaneousGesture(dragGesture) // for horizontal swipe
}
// ...
}
}
I've discovered an issue with using iOS 16's Transferable drag-and-drop APIs for SwiftUI. The dropDestination modifier does not work when applied to a subview of a List.
This code below will not work, unless you replace the List with a VStack or any other container (which, of course, removes all list-specific rendering).
The draggable modifier will still work and the item will drag, but the dropDestination view won't react to it and neither closure will be called.
struct MyView: View {
var body: some View {
List {
Section {
Text("drag this title")
.font(.largeTitle)
.draggable("a title")
}
Section {
Color.pink
.frame(width: 400, height: 400)
.dropDestination(for: String.self) { receivedTitles, location in
true
} isTargeted: {
print($0)
}
}
}
}
}
Has anyone encountered this bug and perhaps found a workaround?
We're seeing sporadic crashes on devices running iOS 18.1 - both beta and release builds (22B83). The stack trace is always identical, a snippet of it below. As you can tell from the trace, it's happening in places we embed SwiftUI into UIKit via UIHostingController.
Anyone else seeing this?
4 libobjc.A.dylib 0xbe2c _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30
5 libobjc.A.dylib 0xb040 weak_register_no_lock + 396
6 libobjc.A.dylib 0xac50 objc_storeWeak + 472
7 libswiftCore.dylib 0x43ac34 swift_unknownObjectWeakAssign + 24
8 SwiftUI 0xeb74c8 _UIHostingView.base.getter + 160
9 SwiftUI 0x92124 _UIHostingView.layoutSubviews() + 112
10 SwiftUI 0x47860 @objc _UIHostingView.layoutSubviews() + 36
Hi
I am using PhotosPicker and SwiftData with iOS17.0.
I released my own app using codes of two above. No problem came up right until I upgraded my iphone to iOS 18.0 17th of September 24. A single post pokes the similar problem. SwiftData and PhotosPikcer. He or She said it was about SwiftData Model Insert something. But, I was able to use other methods that use SwiftData, so insert Model setup isn't my problem.
But when tapping a photo to get a photo from PhotosPicker makes the ui goes down, and navigate back. Weird. iIt doesnt crash but when I tap a photo, the debug message [ERROR] Could not create a bookmark: NSError: Cocoa 4097 "connection to service named com.apple.FileProvider" comes up and the view navigates back.
The selecting a photo itself doesnt include any SwiftData related methods, it only does loadTransferable thing and shows the photo on the screen.
I cannot understand it. it only happened when I upgraded to iOS 18.0. AND Then i debugged the prob with Xcode 16.0 nothing but the unexpected message appears and not many posts are up here or google. Can you help me?
Things I tried:
Check any use of the PhotosPickerItem anywhere else. -> No where.
Use try await loadTransferable
Changed the form of initiating PhotosPikcer View
Debugging every line -> Nothing appeared.
PhotosPicker(selection: $currentImage, matching: .images, photoLibrary: .shared()) {
Text("")
}
.frame(height: 360)
.photosPickerStyle(.inline)
.photosPickerAccessoryVisibility(.hidden, edges: .bottom)
.photosPickerDisabledCapabilities(.selectionActions)
.onChange(of: currentImage) { _, newImage in
// SomeLogic
}
.ignoresSafeArea(edges: .bottom)
.transition(.move(edge: .bottom).combined(with: .opacity))
Generic parameter 'V' could not be inferred ERROR
In my project, I am getting some text from backend which could have html tags. For this, I am converting the string to attributed string. However I noticed that when the string has html tags with color in it and when the text is displayed in toolbar, then the text displays with an ellipsis towards the end. Sharing code below:
import SwiftUI
struct ContentViewA: View {
@State private var displayText: AttributedString?
var body: some View {
NavigationStack {
VStack {
Text(displayText ?? "")
}
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button {
} label: {
Text("Done").font(.body.bold())
}
}
ToolbarItem(placement: .principal) {
Text(displayText ?? "")
}
}
.onAppear {
let string = "<div><p><span style=\"color:#FF0000;\">Hello World</span></p></div>"
displayText = string.convertToAttributedString
/// Note: If I don't set the font, then the ellipsis are not displayed in the toolbar, but I need this font style.
displayText?.font = .body.bold()
}
}
}
}
extension String {
var convertToAttributedString: AttributedString? {
guard let data = data(using: .utf8) else { return nil }
var attributedString: AttributedString?
if let nsAttributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil) {
attributedString = try? AttributedString(nsAttributedString, including: \.uiKit)
}
return attributedString
}
}
I am printing displayText in the body of the view and am not seeing ellipsis at the end of the string, but in toolbar, I am seeing ellipsis. I am unable to figure out what's causing this and what can be the fix for it. However, if I avoid setting the font on attributed string, then the ellipsis are not displayed in toolbar. However, I need to set the string to a specific font style.
How can I avoid ellipsis in toolbar and while also setting the required font on the string?
Topic:
UI Frameworks
SubTopic:
SwiftUI
I'm trying to implement the same UI used by the Settings app on iPad: a split view with two columns that are visible at all times.
This code produces the layout i want, but I would like to hide the "toggle sidebar visibility" button that the system introduces.
Is there a SwiftUI API I can use to hide this button? Maybe an alternate way to setup views that tells the system that the button is not necessary?
struct SomeView: View {
var body: some View {
NavigationSplitView(
columnVisibility: .constant(.all),
sidebar: { Text("sidebar") },
detail: { Text("detail") }
)
.navigationSplitViewStyle(.balanced)
}
}
In iOS 18.4.1, DocumentGroup contains the DocumentView twice. (this may cause issues with alerts)
To reproduce (iOS 18.4):
In XCode Version 16.3 (16E140), create new project. Choose iOS, "Document App". No need to make code changes.
Compile and run app on iOS 18.4 (simulator or device).
in iOS (sim or device): Tap create document (once the app launched).
in XCode: click "Debug View Hierarchy"
in XCode: rotate the view Hierarch to reveal duplicated Document View hierarchies (2 Document Hosting Controllers), see screenshot.
This probably affects alert view... I get warnings and it does not work properly (used to work ok on previous versions).
Previous versions
To compare with previous versions of iOS, run the same code and procedure on iOS 18.3 for example (see screenshot).
Will report on Feedback assistant as well...
I've posted a couple times now about major issues I'm having with NSLayoutManager and have written to Apple for code-level support, but no one at Apple has responded to me in more than two weeks. So I'm turning to the community again for any help whatsoever.
I'm fairly certain it's a real bug in TextKit. If I'm right about that, I'd love for anyone at Apple to take an interest. And better yet, if I'm wrong (and I hope I am), I'd be incredibly grateful to anyone who can point out where my mistake lies! I've been stuck with this bug for weeks on end.
The crux of the issue is that I'm getting what seemed to be totally incompatible results from back to back calls to textContainer(forGlyphAt:effectiveRange:) and lineFragmentRect(forGlyphAt:effectiveRange:withoutAdditionalLayout:)... I'd lay out my text into a fairly tall container of standard page width and then query the layout manager for the text container and line fragment rect for a particular glyph (a glyph that happens to fall after many newlines). Impossibly, the layout manager would report that that glyph was in said very tall container, but that the maxY of its lineFragmentRect was only at 14 points (my NSTextView's isFlipped is true, so that's 14 points measuring from the top down).
After investigating, it appears that what is happening under the hood is NSLayoutManager is for some reason laying out text back into the first container in my series of containers, rather than overflowing it into the next container(s) and/or giving me a nil result for textContainer(forGlyphAt:...)
I've created a totally stripped down version of my project that recreates this issue reliably and I'm hoping literally anyone at Apple will respond to me. In order to recreate the bug, I've had to build a very specific set of preview data - namely some NSTextStorage content and a unique set of NSTextViews / NSTextContainers.
Because of the unique and particular setup required to recreate this bug, the code is too much to paste here (my preview data definition is a little unwieldy but the code that actually processes/parses it is not).
I can share the project if anyone is able and willing to look into this with me. It seems I'm not able to share a .zip of the project folder here but am happy to email or share a dropbox link.
In creating a sequenced gesture combining a LongPressGesture and a DragGesture, I found that the combined gesture exhibits two problems:
The @GestureState does not properly update as the gesture progresses through its phases. Specifically, the updating(_:body:) closure (documented here) is only ever executed during the drag interaction. Long presses and drag-releases do not call the updating(_:body:) closure.
Upon completing the long press gesture and activating the drag gesture, the drag gesture remains empty until the finger or cursor has moved. The expected behavior is for the drag gesture to begin even when its translation is of size .zero.
This second problem – the nonexistence of a drag gesture once the long press has completed – prevents access to the location of the long-press-then-drag. Access to this location is critical for displaying to the user that the drag interaction has commenced.
The below code is based on Apple's example presented here. I've highlighted the failure points in the code with // *.
My questions are as follows:
What is required to properly update the gesture state?
Is it possible to have a viable drag gesture immediately upon fulfilling the long press gesture, even with a translation of .zero?
Alternatively to the above question, is there a way to gain access to the location of the long press gesture?
import SwiftUI
import Charts
enum DragState {
case inactive
case pressing
case dragging(translation: CGSize)
var isDragging: Bool {
switch self {
case .inactive, .pressing:
return false
case .dragging:
return true
}
}
}
struct ChartGestureOverlay<Value: Comparable & Hashable>: View {
@Binding var highlightedValue: Value?
let chartProxy: ChartProxy
let valueFromChartProxy: (CGFloat, ChartProxy) -> Value?
let onDragChange: (DragState) -> Void
@GestureState private var dragState = DragState.inactive
var body: some View {
Rectangle()
.fill(Color.clear)
.contentShape(Rectangle())
.onTapGesture { location in
if let newValue = valueFromChartProxy(location.x, chartProxy) {
highlightedValue = newValue
}
}
.gesture(longPressAndDrag)
}
private var longPressAndDrag: some Gesture {
let longPress = LongPressGesture(minimumDuration: 0.2)
let drag = DragGesture(minimumDistance: .zero)
.onChanged { value in
if let newValue = valueFromChartProxy(value.location.x, chartProxy) {
highlightedValue = newValue
}
}
return longPress.sequenced(before: drag)
.updating($dragState) { value, gestureState, _ in
switch value {
case .first(true):
// * This is never called
gestureState = .pressing
case .second(true, let drag):
// * Drag is often nil
// * When drag is nil, we lack access to the location
gestureState = .dragging(translation: drag?.translation ?? .zero)
default:
// * This is never called
gestureState = .inactive
}
onDragChange(gestureState)
}
}
}
struct DataPoint: Identifiable {
let id = UUID()
let category: String
let value: Double
}
struct ContentView: View {
let dataPoints = [
DataPoint(category: "A", value: 5),
DataPoint(category: "B", value: 3),
DataPoint(category: "C", value: 8),
DataPoint(category: "D", value: 2),
DataPoint(category: "E", value: 7)
]
@State private var highlightedCategory: String? = nil
@State private var dragState = DragState.inactive
var body: some View {
VStack {
Text("Bar Chart with Gesture Interaction")
.font(.headline)
.padding()
Chart {
ForEach(dataPoints) { dataPoint in
BarMark(
x: .value("Category", dataPoint.category),
y: .value("Value", dataPoint.value)
)
.foregroundStyle(highlightedCategory == dataPoint.category ? Color.red : Color.gray)
.annotation(position: .top) {
if highlightedCategory == dataPoint.category {
Text("\(dataPoint.value, specifier: "%.1f")")
.font(.caption)
.foregroundColor(.primary)
}
}
}
}
.frame(height: 300)
.chartOverlay { chartProxy in
ChartGestureOverlay<String>(
highlightedValue: $highlightedCategory,
chartProxy: chartProxy,
valueFromChartProxy: { xPosition, chartProxy in
if let category: String = chartProxy.value(atX: xPosition) {
return category
}
return nil
},
onDragChange: { newDragState in
dragState = newDragState
}
)
}
.onChange(of: highlightedCategory, { oldCategory, newCategory in
})
}
.padding()
}
}
#Preview {
ContentView()
}
Thank you!
Is the Cancel button intentionally removed from UISearchBar (right side)?
Even when using searchController with navigationItem also.
showsCancelButton = true
doesn’t display the cancel button.
Also:
When tapping the clear ("x") button inside the search field, the search is getting canceled, and searchBarCancelButtonClicked(_:) is triggered (Generally it should only clear text, not cancel search).
If the search text is empty and I tap outside the search bar, the search is canceled.
Also when I have tableview in my controller(like recent searches) below search bar and if I try to tap when editing started, action is not triggered(verified in sample too). Just cancellation is happening.
In a split view controller, if the search is on the right side and I try to open the side panel, the search also gets canceled.
Are these behaviors intentional changes, beta issues, or are we missing something in implementation?
This issue was in the first iOS 26 beta and it still there with Xcode 26 beta 6 (17A5305f). Feedback is FB18581605 and contains sample project to reproduce the issue.
I assign a target and action to a UISlider for the UIControl.Event.valueChanged value:
addTarget(self, action: #selector(sliderValueDidChange), for: .valueChanged)
Here’s the function.
@objc
func sliderValueDidChange(_ sender: UISlider, event: UIEvent) {
print(event)
}
When printing the event value, there is a crash. When checking the event value with lldb, it appears uninitialized.
I need to check the network connection with NWPathMonitor.
import Foundation
import Network
class NetworkViewModel: ObservableObject {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "NetworkViewModel")
@Published var isConnected = false
var connectionDescription: String {
if isConnected {
return "You are connected."
} else {
return "You are NOT connected."
}
}
init() {
monitor.pathUpdateHandler = { path in
DispatchQueue.main.async {
self.isConnected = path.status == .satisfied
}
}
monitor.start(queue: queue)
}
}
import SwiftUI
struct ContentView: View {
@StateObject private var networkViewModel = NetworkViewModel()
var body: some View {
VStack {
}
.onAppear {
if networkViewModel.isConnected {
print("You are connected.")
}
else {
print("You are NOT connected.")
}
}
}
}
So there is nothing special, not at all. Yet, if I test it with a totally new Xcode project for iOS, it fails and return !isConnected. I've tested it with a macOS application. And it fails. I've tested it with an actual device. It fails. I've tested it with an old project. It still does work. I have no mere idea why new Xcode projects all fail to detect the WiFi connection. This is a total nightmare. Does anybody have a clue? thanks.
When I update a variable inside my model that is marked @Transient, my view does not update with this change. Is this normal? If I update a non-transient variable inside the model at the same time that I update the transient one, then both changes are propagated to my view.
Here is an example of the model:
@Model public class WaterData {
public var target: Double = 3000
@Transient public var samples: [HKQuantitySample] = []
}
Updating samples only does not propagate to my view.
Dear Sirs,
I'm writing an audio application that should show up to 128 horizontal peakmeters (width for each is about 150, height is 8) stacked inside a ScrollViewReader. For the actual value of the peakmeter I have a binding to a CGFloat value. The peakmeter works as expected and is refreshing correct. For testing I added a timer to my swift application that is firing every 0.05 secs, meaning I want to show 20 values per second. Inside the timer func I'm just creating random CGFloat values in range of 0...1 for the bound values. The peakmeters refresh and flicker as expected but I can see a CPU load of 40-50% in the activity monitor on my MacBook Air with Apple M2 even when compiled in release mode. I think this is quite high and I'd like to reduce this CPU load. Should this be possible? I.e. I thought about blocking the refresh until I've set all values? How could this be done and would it help? What else could I do?
Thanks and best regards,
JFreyberger
I have arrived at a certain architectural solution for my SwiftUI code which is helped by, in certain situations, modifying the state while the body is being evaluated.
Of course, I am always open to realizing that a given solution may be creating difficulties precisely because it is fundamentally ill-advised. However, in this post I won't attempt to explain the details of my architecture or justify my reasoning regarding wanting to change the state in the middle of a view update. I just want to ask, why exactly is it prohibited? Is it not rather like normal recursion, which can of course produce infinite loops if done wrong but which is perfectly logically sound as long as the recursing function eventually stabilizes?
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi! I develop an iOS library and I met an issue with SwiftUI previews in iOS app project with my library integrated. After I open preview, build for preview finishes successfully, but preview itself never appears. I failed to find any error messages or any other indicators of what went wrong or how to fix it. Switching to legacy preview execution seems to fix problem, but I think that is not ideal. Could you help fixing this?
Xcode 16.2, Simulator iPhone 16, iOS 18.2
Project to reproduce -
https://drive.google.com/file/d/1cU6JKwshK_wQfe9YIqcMg3UGWq45OYlx/view?usp=sharing
Preview diagnostics - https://drive.google.com/file/d/1kPcgVSSqreiepGuqhdIoCW2rLSicgsWr/view?usp=sharing
I'm trying to piece together how I should reason about multiple windows, activating menus and items.
For instance, I have an email command. If a document is open, it emails just that document. If the collection view holding that document is open, it generates an attachment representing the collection. (this happens with buttons right now but this really feels like a menu item) How do I tell which window is active (document/collection) in order to have the right menu item available.
If the user is adding a document I don't want the "new" command open, I only want one editing view. I saw sample code to include or remove commands but not disable them. I feel like there's a whole conceptual layer I want to understand with the interplay with scenes but don't know where to look for documentation. I searched here but there's hardly any threads on this.
TIA
Topic:
UI Frameworks
SubTopic:
UIKit