I am trying to build a text editor that shrinks to its content size. The closest I have been able to get has been to add the .scrollDisabled(true) and .fixedSize(horizontal: false, vertical: true) modifiers.
This almost achieves what I need. There are two problems though:
long single line text gets cut off at the end
creating line breaks causes the text editor to grow vertically as expected (uncovering the cut off text in point 1 above). However, when you delete the line breaks, the TextEditor does not shrink again.
I have had a radar open for some time: FB13292506. Hopefully opening a thread here will get more visibility.
And here is some sample code to easily reproduce the issue:
import SwiftUI
struct ContentView: View {
@State var text = "[This is some long text that will be cut off at the end of the text editor]"
var body: some View {
TextEditor(text: $text)
.scrollDisabled(true)
.fixedSize(horizontal: false, vertical: true)
}
}
#Preview {
ContentView()
}
Here is a gif of the behavior:
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I’m so lost on this. I’ve tried Google, ChatGPT, DeepSeek, the documentation. I’ve spent about 7 hours on this specific bug. Not sure what to do next. Does anyone have an idea?
I've been thinking a lot about how navigation and presentation are managed in SwiftUI, and I wanted to propose an idea for a more streamlined approach using environment values. Right now, handling navigation can feel fragmented — especially when juggling default NavigationStack, modals, and tab selections.
What if SwiftUI provided a set of convenience environment values for these common actions?
Tabs
@Environment(\.selectedTab) var selectedTab
@Environment(\.selectTab) var selectTab
selectedTab: Read the current tab index
selectTab(index: Int): Programmatically switch tabs
Stack Navigation
@Environment(\.stackCount) var stackCount
@Environment(\.push) var push
@Environment(\.pop) var pop
@Environment(\.popToRoot) var popToRoot
stackCount: Read how many views are in the navigation stack
push(destination: View): Push a new view onto the stack
pop(last: Int = 1): Pop the last views
popToRoot(): Return to the root view
Modals
@Environment(\.sheet) var sheet
@Environment(\.fullScreenCover) var fullScreenCover
@Environment(\.popover) var popover
@Environment(\.dismissModal) var dismissModal
sheet(view: View): Present a sheet
fullScreenCover(view: View): Present a full-screen cover
popover(view: View): Show a popover
dismissModal(): Dismiss any presented modal
Alerts & Dialogs
@Environment(\.alert) var alert
@Environment(\.confirmationDialog) var confirmationDialog
@Environment(\.openAppSettings) var openAppSettings
alert(title: String, message: String): Show an alert
confirmationDialog(title: String, actions: [Button]): Show a confirmation dialog
openAppSettings(): Directly open the app’s settings
Why?
Clean syntax: This keeps navigation code clean and centralized.
Consistency: Environment values already manage other app-level concerns (color scheme, locale, etc.). Why not navigation too?
Reusability: This approach is easy to adapt across different view hierarchies.
Example
@main
struct App: App {
var body: some Scene {
WindowGroup {
TabView {
NavigationStack {
ProductList()
}
.tabItem { ... }
NavigationStack {
OrderList()
}
.tabItem { ... }
}
}
}
}
struct ProductList: View {
@Environment(\.push) var push
@State var products: [Product] = []
var body: some View {
List(protucts) { product in
Button {
push(destination: ProductDetails(product: product))
}
} label: {
...
}
}
.task { ... }
}
}
struct ProductDetails: View { ... }
When trying to debug a mysterious app crash pointing to some layoutIfNeeded() method call, me and my QA team member reduced it to this sample app.
struct ContentView: View {
@State var isPresented = false
var body: some View {
VStack {
Button {
isPresented = true
} label: {
Text("show popover")
}
.popover(isPresented: $isPresented) {
Text("hello world")
}
}
.padding()
}
}`
This code crashes on his iPad iOS 18.1.0 22B5034E with EXC_BAD_ACCESS error. It is not reproducible on simulator or on device with iOS 18.2 or iOS 17.
Is this a known issue? Are there any known workarounds? I've found similar posts here
https://developer.apple.com/forums/thread/769757
https://developer.apple.com/forums/thread/768544
But they are about more specific cases.
I want to get to a point where I can use a small view with a query for my SwiftData model like this:
@Query
private var currentTrainingCycle: [TrainingCycle]
init(/*currentDate: Date*/) {
_currentTrainingCycle = Query(filter: #Predicate<TrainingCycle> {
$0.numberOfDays > 0
// $0.startDate < currentDate && currentDate < $0.endDate
}, sort: \.startDate)
}
The commented code is where I want to go. In this instance, it'd be created as a lazy var in a viewModel to have it stable (and not constantly re-creating the view). Since it was not working, I thought I could check the same view with a query that does not require any dynamic input. In this case, the numberOfDays never changes after instantiation.
But still, each time the app tries to create this view, the app becomes unresponsive, the CPU usage goes at 196%, memory goes way high and the device heats up quickly.
Am I holding it wrong? How can I have a dynamic predicate on a View in SwiftUI with SwiftData?
The issue I'm facing arise when using a lazyvstack within a navigationstack. I want to use the pinnedViews: .sectionHeaders feature from the lazyStack to display a section header while rendering the content with a scrollview. Below is the code i'm using and at the end I share a sample of the loop issue:
struct SProjectsScreen: View {
@Bindable var store: StoreOf<ProjectsFeature>
@State private var searchText: String = ""
@Binding var isBotTabBarHidden: Bool
@Environment(\.safeArea) private var safeArea: EdgeInsets
@Environment(\.screenSize) private var screenSize: CGSize
@Environment(\.dismiss) var dismiss
private var isLoading : Bool {
store.projects.isEmpty
}
var body: some View {
NavigationStack(path:$store.navigationPath.sending(\.setNavigationPath)) {
ScrollView(.vertical){
LazyVStack(spacing:16,pinnedViews: .sectionHeaders) {
Section {
VStack(spacing:16) {
if isLoading {
ForEach(0..<5,id:\.self) { _ in
ProjectItemSkeleton()
}
}
else{
ForEach(store.projects,id:\._id) { projectItem in
NavigationLink(value: projectItem) {
SProjectItem(project: projectItem)
.foregroundStyle(Color.theme.foreground)
}
.simultaneousGesture(TapGesture().onEnded({ _ in
store.send(.setCurrentProjectSelected(projectItem.name))
}))
}
}
}
} header: {
VStack(spacing:16) {
HStack {
Text("Your")
Text("Projects")
.fontWeight(.bold)
Text("Are Here!")
}
.font(.title)
.frame(maxWidth: .infinity,alignment: .leading)
.padding(.horizontal,12)
.padding(.vertical,0)
HStack {
SSearchField(searchValue: $searchText)
Button {
} label: {
Image(systemName: "slider.horizontal.3")
.foregroundStyle(.white)
.fontWeight(.medium)
.font(.system(size: 24))
.frame(width:50.66,height: 50.66)
.background {
Circle().fill(Color.theme.primary)
}
}
}
}
.padding(.top,8)
.padding(.bottom,16)
.background(content: {
Color.white
})
}
}
}
.scrollIndicators(.hidden)
.navigationDestination(for: Project.self) { project in
SFoldersScreen(project:project,isBotTabBarHidden: $isBotTabBarHidden)
.toolbar(.hidden)
}
.padding(.horizontal,SScreenSize.hPadding)
.onAppear {
Task {
if isLoading{
do {
let projectsData = try await ProjectService.Shared.getProjects()
store.send(.setProjects(projectsData))
}
catch{
print("error found: ",error.localizedDescription)
}
}
}
}
.refreshable {
do {
let projectsData = try await ProjectService.Shared.getProjects()
store.send(.setProjects(projectsData))
}
catch{
print("error found: ",error.localizedDescription)
}
}
}.onChange(of: store.navigationPath, { a, b in
print("Navigation path changed:", b)
})
}
}
I'm using tca library for managing states so this is my project feature reducer:
import ComposableArchitecture
@Reducer
struct ProjectsFeature{
@ObservableState
struct State: Equatable{
var navigationPath : [Project] = []
var projects : [Project] = [
]
var currentProjectSelected : String?
}
enum Action{
case setNavigationPath([Project])
case setProjects([Project])
case setCurrentProjectSelected(String?)
case popNavigation
}
var body: some ReducerOf<Self> {
Reduce { state, action in
switch action {
case .setNavigationPath(let navigationPath):
state.navigationPath = navigationPath
return .none
case .setProjects(let projects):
state.projects = projects
return .none
case .setCurrentProjectSelected(let projectName):
state.currentProjectSelected = projectName
return .none
case .popNavigation:
if !state.navigationPath.isEmpty {
state.navigationPath.removeLast()
}
state.currentProjectSelected = nil
return .none
}
}
}
I want to show a view, where the user can add or remove items shown as icons, which are sorted in two groups: squares and circles.
When there are only squares, they should be shown in one row:
[] [] []
When there are so many squares that they don’t fit horizontally, a (horizontal) scrollview will be used, with scroll-indicator always shown to indicate that not all squares are visible.
When there are only circles, they also should be shown in one row:
() () ()
When there are so many circles that they don’t fit horizontally, a (horizontal) scrollview will be used, with scroll-indicator always shown to indicate that not all circles are visible.
When there a few squares and a few circles, they should be shown adjacent in one row:
[] [] () ()
When there are so many squares and circles that they don’t fit horizontally, they should be shown in two rows, squares on top, circles below:
[] [] []
() () ()
When there are either too many squares or too many circles (or both) to fit horizontally, one common (horizontal) scrollview will be used, with scroll-indicator always shown to indicate that not all items are visible.
I started with ViewThatFits: (see first code block)
{
let squares = HStack {
ForEach(model.squares, id: \.self) { square in
Image(square)
}
}
let circles = HStack {
ForEach(model.circles, id: \.self) { circle in
Image(circle)
}
}
let oneLine = HStack {
squares
circles
}
let twoLines = VStack {
squares
circles
}
let scrollView = ScrollView(.horizontal) {
twoLines
}.scrollIndicators(.visible)
ViewThatFits(in: .horizontal) {
oneLine
twoLines
scrollView.clipped()
}
}
While this works in general, it doesn’t animate properly.
When the user adds or removes an image the model gets updated, (see second code block)
withAnimation(Animation.easeIn(duration: 0.25)) {
model.squares += image
}
and the view animates with the existing images either making space for a new appearing square/circle, or moving together to close the gap where an image disappeared.
This works fine as long as ViewThatFits returns the same view.
However, when adding 1 image leads to ViewThatFits switching from oneLine to twoLines, this switch is not animated. The circles jump to the new position under the squares, instead of sliding there.
I searched online for a solution, but this seems to be a known problem of ViewThatFits. It doesn't animate when it switches...
(tbc)
UIKit and SwiftUI each have their own strengths and weaknesses:
UIKit: More performant (e.g., UICollectionView).
SwiftUI: Easier to create shiny UI and animations.
My usual approach is to base my project on UIKit and use UIHostingController whenever I need to showcase visually rich UI or animations (such as in an onboarding presentation).
So far, this approach has worked well for me—it keeps the project clean while solving performance concerns effectively.
However, I was wondering: Has anyone tried the opposite approach?
Creating a project primarily in SwiftUI, then embedding UIKit when performance is critical.
If so, what has your experience been like? Would you recommend this approach?
I'm considering this for my next project but am unsure how well it would work in practice.
Simple master screen with list, NavigationLink to editable detail view.
I want edits on the detail screen to update to the master list "cars" variable and the list UI.
On the detail view, if I edit one field and exit the field, the value reverts to the original value. Why?
If I edit one field, don't change focus and hit the back button. The master list updates. This is what I want, but I can only update 1 field because of problem #1. Should be able to edit all the fields.
If I implement the == func in the Car struct, then no updates get saved. Why?
struct Car: Hashable, Equatable {
var id: UUID = UUID()
var make: String
var model: String
var year: Int
// static func == (lhs: Car, rhs: Car) -> Bool {
// return lhs.id == rhs.id
// }
}
struct ContentView: View {
@State private var cars: [Car]
init() {
cars = [
Car(make: "Toyota", model: "Camry", year: 2020),
Car(make: "Honda", model: "Civic", year: 2021),
Car(make: "Ford", model: "Mustang", year: 2022),
Car(make: "Chevrolet", model: "Malibu", year: 2023),
Car(make: "Nissan", model: "Altima", year: 2024),
Car(make: "Kia", model: "Soul", year: 2025),
Car(make: "Volkswagen", model: "Jetta", year: 2026)
]
}
var body: some View {
NavigationStack {
VStack {
ForEach($cars, id: \.self) { $car in
NavigationLink(destination: CarDetailView(car: $car)){
Text(car.make)
}
}
}
}
}
}
struct CarDetailView: View {
@Binding var car: Car
var body: some View {
Form {
TextField("Make", text: $car.make)
TextField("Model", text: $car.model)
TextField("Year", value: $car.year, format: .number)
}
}
}
How do I filter data using @Query with a Set of DateComponents? I successfully saved multiple dates using a MultiDatePicker in AddView.swift. In ListView.swift, I want to retrieve all records for the current or today’s date.
There are hundreds of examples using @Query with strings and dates, but I haven’t found an example of @Query using a Set of DateComponents
Nothing will compile and after hundreds and hundreds of attempts, my hair is turning gray.
Please, please, please help me.
For example, if the current date is Tuesday, March 4 205, then I want to retrieve both records. Since both records contain Tuesday, March 4, then retrieve both records. Sorting works fine because the order by clause uses period which is a Double.
Unfortunately, my syntax is incorrect and I don’t know the correct predicate syntax for @Query and a Set of DateComponents.
Class Planner.swift file
import SwiftUI
import SwiftData
@Model
class Planner {
//var id: UUID = UUID()
var grade: Double = 4.0
var kumi: Double = 4.0
var period: Double = 1.0
var dates: Set<DateComponents> = []
init(
grade: Double = 4.0, kumi: Double = 4.0, period: Double = 1.0, dates: Set<DateComponents> = []
)
{
self.grade = grade
self.kumi = kumi
self.period = period
self.dates = dates
}
}
@Query Model snippet of code does not work
The compile error is to use a Set of DateComponents, not just DateComponents.
@Query(filter: #Predicate<Planner> { $0.dates = DateComponents(calendar: Calendar.current, year: 2025, month: 3, day: 4)},
sort: [SortDescriptor(\Planner.period)])
var planner: [Planner]
ListView.swift image
EditView.swift for record #1
DB Browser for SQLlite: record #1 (March 6, 2025 and March 4, 2025)
[{"isLeapMonth":false,"year":2025,"day":6,"month":3,"calendar":{"identifier":"gregorian","minimumDaysInFirstWeek":1,"current":1,"locale":{"identifier":"en_JP","current":1},"firstWeekday":1,"timeZone":{"identifier":"Asia\/Tokyo"}},"era":1},{"month":3,"year":2025,"day":4,"isLeapMonth":false,"era":1,"calendar":{"locale":{"identifier":"en_JP","current":1},"timeZone":{"identifier":"Asia\/Tokyo"},"current":1,"identifier":"gregorian","firstWeekday":1,"minimumDaysInFirstWeek":1}}]
EditView.swift for record #2
DB Browser for SQLlite: record #2 (March 3, 2025 and March 4, 2025)
[{"calendar":{"minimumDaysInFirstWeek":1,"locale":{"current":1,"identifier":"en_JP"},"timeZone":{"identifier":"Asia\/Tokyo"},"firstWeekday":1,"current":1,"identifier":"gregorian"},"month":3,"day":3,"isLeapMonth":false,"year":2025,"era":1},{"year":2025,"month":3,"era":1,"day":4,"isLeapMonth":false,"calendar":{"identifier":"gregorian","current":1,"firstWeekday":1,"minimumDaysInFirstWeek":1,"timeZone":{"identifier":"Asia\/Tokyo"},"locale":{"current":1,"identifier":"en_JP"}}}]
Any help is greatly appreciated.
In my app, I have a ShareLink that attempts to share a movie.
struct MovieTransferable: Transferable {
let url: URL
let writeMovie: (URL) -> ()
static var transferRepresentation: some TransferRepresentation {
DataRepresentation(
exportedContentType: .movie,
exporting: {
(movie) in
// Write the movie into documents.
movie.writeMovie(movie.url)
return try! Data(contentsOf: movie.url)
})
FileRepresentation(
exportedContentType: .movie,
exporting: {
(movie) in
// Write the movie into documents.
movie.writeMovie(movie.url)
return SentTransferredFile(movie.url)
})
}
}
The ShareLink works if you try to share the movie with the Photos app, Air Drop, and iMessage. If I share to WhatsApp, the movie shows up as empty (zero length), but there's a movie. If I share to Discord, the movie is not displayed at all (only the comment). Instagram posts a dialog saying it won't allow movies and to use the app (why are they even in the ShareLink option for movies?). YouTube processes for a bit and then does nothing (no upload).
Are there things that I can do to make the Transferable accepted at more of the end points? It's at fps 30 and I've tried most of the available codec's. The size is the same as the iPhone's screen, so the aspect ratio is a bit odd. However, if I go directly to the app (Discord, etc...) upload from my phone works fine.
Any help would be appreciated to make this more viable.
Hello Apple Developer Community,
I’m facing a recurring issue in my SwiftUI iOS app where a specific view fails to reload correctly after saving edits and navigating back to it. The failure happens consistently post-save, and I’m looking for insights from the community.
🛠 App Overview
Purpose
A SwiftUI app that manages user-created data, including images, text fields, and completion tracking.
Tech Stack:
SwiftUI, Swift 5.x
MSAL for authentication
Azure Cosmos DB (NoSQL) for backend data
Azure Blob Storage for images
Environment:
Xcode 15.x
iOS 17 (tested on iOS 18.2 simulator and iPhone 16 Pro)
User Context:
Users authenticate via MSAL.
Data is fetched via Azure Functions, stored in Cosmos DB, and displayed dynamically.
🚨 Issue Description
🔁 Steps to Reproduce
Open a SwiftUI view (e.g., a dashboard displaying a user’s saved data).
Edit an item (e.g., update a name, upload a new image, modify completion progress).
Save changes via an API call (sendDataToBackend).
The view navigates back, but the image URL loses its SAS token.
Navigate away (e.g., back to the home screen or another tab).
Return to the view.
❌ Result
The view crashes, displays blank, or fails to load updated data.
SwiftUI refreshes text-based data correctly, but AsyncImage does not.
Printing the image URL post-save shows that the SAS token (?sv=...) is missing.
❓ Question
How can I properly reload AsyncImage after saving, without losing the SAS token?
🛠 What I’ve Tried
✅ Verified JSON Structure
Debugged pre- and post-save JSON.
Confirmed field names match the Codable model.
✅ Forced SwiftUI to Refresh
Tried .id(UUID()) on NavigationStack:
NavigationStack {
ProjectDashboardView()
.id(UUID()) // Forces reinit
}
Still fails intermittently.
✅ Forced AsyncImage to Reload
Tried appending a UUID() to the image URL:
AsyncImage(url: URL(string: "\(imageUrl)?cacheBust=\(UUID().uuidString)"))
Still fails when URL query parameters (?sv=...) are trimmed.
I’d greatly appreciate any insights, code snippets, or debugging suggestions! Let me know if more logs or sample code would help.
Thanks in advance!
I can't get my app's logo to show in the "About" box nor in the app switcher.
I have:
created "Assets.xcassets"
created "AppIcon"
added 10 image files of the logo to the AppIcon image well [? right terminology ?]
saved and built the project – there are no errors or warnings
When I run the project, I still get the default image showing in the About box and in the app switcher.
Because first attempt failed, I changed "applet" to "AppIcon" in "App Icons and Launch Screen" in "General" settings. That did not change the result. I also toggled "Include all app icon assets" which also did not change the result.
Weirdly, my app's logo DOES show beside the app name in every item of "Build Settings".
Do I need to do something else to change the default image in the "About" box ?
Thanks.
[Xcode 16.2 on macOS 15.3.2.]
I am working on an iOS application using SwiftUI where I want to convert a JPG and a MOV file to a live photo. I am utilizing the LivePhoto Class from Github for this. The JPG and MOV files are displayed correctly in my WallpaperDetailView, but I am facing issues when trying to download the live photo to the gallery and generate the Live Photo.
Here is the relevant code and the errors I am encountering:
Console prints:
Play button should be visible Image URL fetched and set: Optional("https://firebasestorage.googleapis.com/...") Video is ready to play Video downloaded to: file:///var/mobile/Containers/Data/Application/.../tmp/CFNetworkDownload_7rW5ny.tmp Failed to generate Live Photo
I have verified that the app has the necessary permissions to access the Photo Library.
The JPEG and MOV files are successfully downloaded and can be displayed in the app.
The issue seems to occur when generating the Live Photo from the downloaded files.
struct WallpaperDetailView: View {
var wallpaper: Wallpaper
@State private var isLoading = false
@State private var isImageSaved = false
@State private var imageURL: URL?
@State private var livePhotoVideoURL: URL?
@State private var player: AVPlayer?
@State private var playerViewController: AVPlayerViewController?
@State private var isVideoReady = false
@State private var showBuffering = false
var body: some View {
ZStack {
if let imageURL = imageURL {
GeometryReader { geometry in
KFImage(imageURL)
.resizable()
...
}
}
if let playerViewController = playerViewController {
VideoPlayerViewController(playerViewController: playerViewController)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.clipped()
.edgesIgnoringSafeArea(.all)
}
}
.onAppear {
PHPhotoLibrary.requestAuthorization { status in
if status == .authorized {
loadImage()
} else {
print("User denied access to photo library")
}
}
}
private func loadImage() {
isLoading = true
if let imageURLString = wallpaper.imageURL, let imageURL = URL(string: imageURLString) {
self.imageURL = imageURL
if imageURL.scheme == "file" {
self.isLoading = false
print("Local image URL set: \(imageURL)")
} else {
fetchDownloadURL(from: imageURLString) { url in
self.imageURL = url
self.isLoading = false
print("Image URL fetched and set: \(String(describing: url))")
}
}
}
if let livePhotoVideoURLString = wallpaper.livePhotoVideoURL, let livePhotoVideoURL = URL(string: livePhotoVideoURLString) {
self.livePhotoVideoURL = livePhotoVideoURL
preloadAndPlayVideo(from: livePhotoVideoURL)
} else {
self.isLoading = false
print("No valid image or video URL")
}
}
private func preloadAndPlayVideo(from url: URL) {
self.player = AVPlayer(url: url)
let playerViewController = AVPlayerViewController()
playerViewController.player = self.player
self.playerViewController = playerViewController
let playerItem = AVPlayerItem(url: url)
playerItem.preferredForwardBufferDuration = 1.0
self.player?.replaceCurrentItem(with: playerItem)
...
print("Live Photo Video URL set: \(url)")
}
private func saveWallpaperToPhotos() {
if let imageURL = imageURL, let livePhotoVideoURL = livePhotoVideoURL {
saveLivePhotoToPhotos(imageURL: imageURL, videoURL: livePhotoVideoURL)
} else if let imageURL = imageURL {
saveImageToPhotos(url: imageURL)
}
}
private func saveImageToPhotos(url: URL) {
...
}
private func saveLivePhotoToPhotos(imageURL: URL, videoURL: URL) {
isLoading = true
downloadVideo(from: videoURL) { localVideoURL in
guard let localVideoURL = localVideoURL else {
print("Failed to download video for Live Photo")
DispatchQueue.main.async {
self.isLoading = false
}
return
}
print("Video downloaded to: \(localVideoURL)")
self.generateAndSaveLivePhoto(imageURL: imageURL, videoURL: localVideoURL)
}
}
private func generateAndSaveLivePhoto(imageURL: URL, videoURL: URL) {
LivePhoto.generate(from: imageURL, videoURL: videoURL, progress: { percent in
print("Progress: \(percent)")
}, completion: { livePhoto, resources in
guard let resources = resources else {
print("Failed to generate Live Photo")
DispatchQueue.main.async {
self.isLoading = false
}
return
}
print("Live Photo generated with resources: \(resources)")
self.saveLivePhotoToLibrary(resources: resources)
})
}
private func saveLivePhotoToLibrary(resources: LivePhoto.LivePhotoResources) {
LivePhoto.saveToLibrary(resources) { success in
DispatchQueue.main.async {
if success {
self.isImageSaved = true
print("Live Photo saved successfully")
} else {
print("Failed to save Live Photo")
}
self.isLoading = false
}
}
}
private func fetchDownloadURL(from gsURL: String, completion: @escaping (URL?) -> Void) {
let storageRef = Storage.storage().reference(forURL: gsURL)
storageRef.downloadURL { url, error in
if let error = error {
print("Failed to fetch image URL: \(error)")
completion(nil)
} else {
completion(url)
}
}
}
private func downloadVideo(from url: URL, completion: @escaping (URL?) -> Void) {
let task = URLSession.shared.downloadTask(with: url) { localURL, response, error in
guard let localURL = localURL, error == nil else {
print("Failed to download video: \(String(describing: error))")
completion(nil)
return
}
completion(localURL)
}
task.resume()
}
}```
Topic:
Media Technologies
SubTopic:
Photos & Camera
Tags:
Files and Storage
Swift
SwiftUI
Photos and Imaging
Hello Apple Developer Support,
I am writing to seek assistance with an issue we are experiencing in our SwiftUI application concerning UI test cases.
Our application uses accessibility labels that differ slightly from the display content to enhance VoiceOver support. However, we have encountered a problem where our UI test cases fail when the accessibility label does not match the actual display content.
Currently, we are using accessibility identifiers in our tests, but they only retrieve the accessibility label, leaving us without a method to access the actual display content. This discrepancy is causing our automated tests to fail, as they cannot verify the visual content of the UI elements.
We would greatly appreciate any guidance or solutions you could provide to address this issue. Specifically, we are looking for a way to ensure our UI tests can access both the accessibility label and the actual display content for verification purposes.
For ex:
Problem scenario - setting accessibilityLabel masks access to any displayed content
If an accessibilityLabel is set on a UI element, then it seems to be no-longer possible to check/access the displayed content of that element:
var body: some View {
Text("AAA")
.accessibilityIdentifier("textThing")
.accessibilityLabel("ZZZ") // Different label from the text which is displayed in UI
}
// in test...
func test_ThingExists() {
XCTAssert(app.staticTexts["AAA"].exists) // Fails, cannot find the element
XCTAssertEqual(app.staticTexts["ZZZ"].label, "AAA") // Fails - '.label' is the accessibilityLabel, not the displayed content
XCTAssertEqual(app.staticTexts["ZZZ"].label, "ZZZ") // Passes, but validates the accessibility content, not the displayed content
XCTAssert(app.staticTexts["textThing"].exists) // Passes, but does not check the displayed content
XCTAssertEqual(app.staticTexts["textThing"].label, "AAA") // Fails - '.label' is the accessibilityLabel, not the displayed content
XCTAssertEqual(app.staticTexts["textThing"].label, "ZZZ") // Passes, but validates the accessibility content, not the displayed content
}
element.label still only checks the accessibilityLabel. There is not, it seems, an way back to being able to check the content of the Text element directly.
Thank you for your attention and support. We look forward to your valuable insights.
Am in the process of migrating some UIKit based apps over to SwiftUI, but for the life of me I cannot find the SwiftUI equivalent of Readable Content Margins.
I have come across some workarounds that kind of, sort of work, but do not produce the same results when compared to running the same user interface written using UIKit on several sizes of iPads in portrait and landscape orientiations.
is it something Apple has not gotten around to yet, because I realize SwiftUI is a work-in-progress, or do we not care about creating consistent readable margins in our apps anymore?
I have found a system bug with UINavigationController, UIGestureRecognizerDelegate mainly the swipe back control.
I have reproduced this in many apps, while some that use custom swipe back i can not reproduce, however any app using default uikit/swift transitions i can reproduce the flicker/previous screen flashing
The Bug: a slight tap or series of quick taps anywhere on the screen (with the slightest (1-2pt -x)confuse the system into thinking its a swipe back gesture, however instead of pushing back to previous screen the UI flickers and flashes the previous screen. for a split second, very easy to reproduce.
on screens with lots of options of boxes to tap it happens quite often.
I have removed all custom "swipe back from anywhere" logic, all custom gesture logic, and can still reproduce by tapping the edge of the screen
with only UINavigationController, UIGestureRecognizerDelegate in my navigation controller.
Please let me know the best way to get in contact with someone at apple to either build an extension to prevent this flicker or if a developer has a fix but this is rarely talked about. (velocity limits etc do not work, and just make the gesture feel awful)
all the developers i have reached out too have looked into this and have said "its an ios bug, only fix is build a custom swipe back from anywhere, or wait for apple to fix it).... as a small indie app, building my own seems daunting
Recap: quick or taps with small x movement flash previous screen instead of pushing back or simply recognizing it as a tap and not flashing previous screen. this happens with no custom code default uikit/swift. Link me your app i can probably reproduce it, I have reproduced it in X(was hard), Retro(easy), and many more.
The goal is to have a smooth native swipe/drag back from anywhere gesture while preventing flicking on fast taps or short taps with minor x movement. i have tried everything from setting limits to -x, velocity limits etc. nothing fixes this.
happy hacking!
PS i hope someone at apple calls me and i can explain this and we can fix it for every app in an update.
I'm having an issue specifically with SwiftUI previews in my iOS project. The project builds and runs fine on devices and simulators (in Rosetta mode), but SwiftUI previews fail to load in both Rosetta and native arm64 simulator environments. The main error in the preview is related to the Alamofire dependency in my SiriKit Intents extension:
Module map file '[DerivedData path]/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.modulemap' not found
This error repeats for multiple Swift files within my SiriKit Intents extension. Additionally, I'm seeing:
Cannot load underlying module for 'Alamofire
Environment
Xcode version: 16.2
macOS version: Sonoma 14.7
Swift version: 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)
Dependency management: CocoaPods
Alamofire version: 5.8
My project is a large, older codebase that contains a mix of UIKit, Objective-C and Swift
Architecture Issue: The project only builds successfully in Rosetta mode for simulators. SwiftUI previews are failing in both Rosetta and native arm64 environments. This suggests there may be a fundamental issue with how the preview system interacts with the project's architecture configuration. What I've Tried I've attempted several solutions without success:
Cleaning the build folder (⇧⌘K and Option+⇧⌘K)
Deleting derived data
Reinstalling dependencies
Restarting Xcode
Removing and re-adding Alamofire
SwiftUI provides the accessibilityCustomContent(_:_:) modifier to add additional accessibility information for an element. However, I couldn’t find a similar approach in UIKit.
Is there a way to achieve this in UIKit?
Hi,
When using SwiftUI ‘List’ with a large number of elements (4000+), I noticed a significant performance issue if extracting the views inside the ‘ForEach’ block into their own subview class. It affects scrolling performance, and using the scroll handle in the scrollbar causes stutters and beachballs. This seems to happen on macOS only ... the same project works fine on iOS.
Here's an example of what I mean:
List (selection: $multiSelectedContacts) {
ForEach(items) { item in
// 1. this subview is the problem ... replace it with the contents of the subview, and it works fine
PlainContentItemView(item: item)
// 2. Uncomment this part for it to work fine (and comment out PlainContentItemView above)
/*HStack {
if let timestamp = item.timestamp, let itemNumber = item.itemNumber {
Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)")
}
}*/
}
}
struct PlainContentItemView: View {
let item: Item
var body: some View {
HStack {
if let timestamp = item.timestamp, let itemNumber = item.itemNumber {
Text("\(itemNumber) - \(timestamp, formatter: itemFormatter)")
}
}
}
}
Item is a NSManagedObject subclass, and conforms to Identifiable by using the objectID string value.
With this, scrolling up and down using the scrolling handle, causes stuttering scrolling and can beachball on my machine (MacBook Pro M1).
If I comment out the ‘PlainContentItemView’ and just use the HStack directly (which is what was extracted to ‘PlainContentItemView’), the performance noticeably improves, and I can scroll up and down smoothly.
Is this just a bug with SwiftUI, and/or can I do something to improve this?