I'm trying to create a Notes-like experience in my SwiftUI app where users can:
Add photos as inline attachments within a TextEditor
Move these attachments around within the text (like they were text characters)
Delete attachments
Preview attachments in full screen
Have the attachments persist with the text content
Similar to how Apple Notes handles attachments, where images become part of the text flow and can be manipulated like text characters.
Current approach:
I've tried using a custom TextEditor with a separate array of attachments, but I'm struggling to make the attachments behave as inline elements that can be moved within the text.
RichTextEditor:
struct RichTextEditor: View {
@State var content: String = ""
@State private var isGalleryPresented = false
@State var pickedImage: PhotosPickerItem?
@State private var selectedImage: UIImage?
var body: some View {
TextEditor(text: $content)
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Button {
isGalleryPresented = true
} label: {
Label("Attached", systemImage: "paperclip")
}
}
}
.photosPicker(isPresented: $isGalleryPresented, selection: $pickedImage)
.onChange(of: pickedImage) { oldItem, newItem in
Task {
if let pickedImage = pickedImage,
let data = try? await pickedImage.loadTransferable(type: Data.self),
let loadedImage = UIImage(data: data) {
if let imageData = loadedImage.jpegData(compressionQuality: 0.7) {
Task {
await addPhoto(imageData)
}
}
}
}
}
}
private func addPhoto(_ imageData: Data) async {
await MainActor.run {
let photo = PhotoData(imageData: imageData)
content += "\n[image:\(photo.id)]"
}
}
}
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
Could anyone help confirm if this is a bug and suggest possible solutions?
Thanksssss
In iOS 18, when using Zoom NavigationTransition, the toolbar from the destination view may randomly appear on the source view after navigating back with the swipe-back gesture.
Re-entering the destination view and navigating back again can temporarily resolve the issue, but it may still occur intermittently.
This bug only happens with Zoom NavigationTransition and does not occur when using a button tap to navigate back.
import SwiftUI
struct test: View {
@Namespace private var namespace
var body: some View {
NavigationStack {
NavigationLink {
Image("img1")
.resizable()
.navigationTransition(.zoom(sourceID: 1, in: namespace))
.toolbar {
ToolbarItem(placement: .bottomBar) {
Text("destination noDisappear")
}
}
} label: {
Image("img1")
.resizable()
.frame(width: 100, height: 100)
.matchedTransitionSource(id: 1, in: namespace)
.toolbar {
ToolbarItem(placement: .bottomBar) {
Text("source toolbar")
}
}
}
}
}
}
Below is my sample code. On the Home page, when I click "show sheet," the sheet page expands, and the StateObject inside the sheet is initialized once. However, when I click "show Fullscreen" and then click "show sheet" inside the fullscreen page, the sheet gets initialized twice.
However, if I remove navigationDestination, this issue does not occur.
This problem causes the network request in the sheet page to be triggered multiple times.
Can someone tell me the reason?
enum TestRouter: String, Hashable {
case test
var targetView: some View {
Text("test")
}
var title: String {
return "test title"
}
}
@MainActor
struct NavigationInnerView<Content>: View where Content: View {
var contentView: () -> Content
@MainActor public init(@ViewBuilder contentView: @escaping () -> Content) {
self.contentView = contentView
}
var body: some View {
NavigationStack() {
contentView()
.navigationDestination(for: TestRouter.self) { route in
route.targetView
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView: View {
@State var showFullScreen: Bool = false
@State var showSheet: Bool = false
var contentView: some View {
VStack {
VStack {
Text("Home")
Button {
showFullScreen = true
} label: {
Text("show fullscreen")
}
Button {
showSheet = true
} label: {
Text("show sheet ")
}
}
}
}
var body: some View {
NavigationInnerView {
contentView
.fullScreenCover(isPresented: $showFullScreen) {
NavigationInnerView {
FullScreenContentView()
}
}
.sheet(isPresented: $showSheet) {
NavigationInnerView {
SheetContentView()
}
}
}
}
}
class FullScreenViewModel: ObservableObject {
@Published var content: Bool = false
init() {
print("Full Screen ViewModel init")
}
}
struct FullScreenContentView: View {
@Environment(\.dismiss) var dismiss
@State var showSheet: Bool = false
@StateObject var viewModel: FullScreenViewModel = .init()
init() {
print("Full screen view init")
}
var body: some View {
VStack {
Text("FullScreen")
Button {
dismiss()
}label: {
Text("dismiss")
}
Button {
showSheet = true
} label: {
Text("show sheet")
}
}
.sheet(isPresented: $showSheet) {
NavigationInnerView {
SheetContentView()
}
}
}
}
class SheetViewModel: ObservableObject {
@Published var content: Bool = false
init() {
print("SheetViewModel init")
}
}
struct SheetContentView: View {
@Environment(\.dismiss) var dismiss
@StateObject var viewModel = SheetViewModel()
init() {
print("sheet view init")
}
var body: some View {
Text("Sheet")
Button {
dismiss()
} label: {
Text("dismiss")
}
}
}
#Preview {
ContentView()
}
SwiftUI Navigation Stack Zoom Transition – Title Animation Issue (iOS 18)
In the WWDC24 video "Enhance your UI animations and transitions", Apple demonstrates how the navigation stack title smoothly animates into the back button in the new view when using a zoom transition:
NavigationLink {
BraceletEditor(bracelet)
.navigationTransitionStyle(
.zoom(
sourceID: bracelet.id,
in: braceletList
)
)
} label: {
BraceletPreview(bracelet)
}
.matchedTransitionSource(
id: bracelet.id,
in: braceletList
)
However, I cannot get this animation.
Expected (from WWDC video):
Actual (iOS 18 simulator):
How can I get the original animation?
Hello!
I’m experiencing a crash in my iOS/iPadOS app related to a CALayer rendering process. The crash occurs when attempting to render a UIImage on a background thread. The crashes are occurring in our production app, and while we can monitor them through Crashlytics, we are unable to reproduce the issue in our development environment.
Relevant Code
I have a custom view controller that handles rendering CALayers onto images. This method creates a CALayer on the main thread and then starts a detached task to render this CALayer into a UIImage. The whole idea is learnt from this StackOverflow post: https://stackoverflow.com/a/77834613/9202699
Here are key parts of my implementation:
class MyViewController: UIViewController {
@MainActor
func renderToUIImage(size: CGSize, itemsToDraw: [MyDrawingItem], transform: CGAffineTransform) async -> UIImage? {
// Create CALayer and add it to the view.
CATransaction.begin()
let customLayer = MyDrawingLayer()
customLayer.setupContent(itemsToDraw: itemsToDraw)
// Position the frame off-screen to it hidden.
customLayer.frame = CGRect(
origin: CGPoint(x: -100 - size.width, y: -100 - size.height),
size: size)
customLayer.masksToBounds = true
customLayer.drawsAsynchronously = true
view.layer.addSublayer(customLayer)
CATransaction.commit()
// Render CALayer to UIImage in background thread.
let image = await Task.detached {
customLayer.setNeedsDisplay()
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { // CRASH happens on this line
let cgContext = $0.cgContext
cgContext.saveGState()
cgContext.concatenate(transform)
customLayer.render(in: cgContext)
cgContext.restoreGState()
}
return image
}.value
// Remove the CALayer from the view.
CATransaction.begin()
customLayer.removeFromSuperlayer()
CATransaction.commit()
return image
}
}
class MyDrawingLayer: CALayer {
var itemsToDraw: [MyDrawingItem] = []
func setupContent(itemsToDraw: [MyDrawingItem]) {
self.itemsToDraw = itemsToDraw
}
override func draw(in ctx: CGContext) {
for item in itemsToDraw {
// Render the item to the context (example pseudo-code).
// All items are thread-safe to use.
// Things to draw may include CGPath, CGImages, UIImages, NSAttributedString, etc.
item.draw(in: ctx)
}
}
}
Crash Log
The crash occurs at the following location:
Crashed: com.apple.root.default-qos.cooperative
0 MyApp 0x5cb300 closure #1 in closure #1 in MyViewController.renderToUIImage(size: CGSize, itemsToDraw: [MyDrawingItem], transform: CGAffineTransform) + 4313002752 (<compiler-generated>:4313002752)
1 MyApp 0x5cb300 closure #1 in closure #1 in MyViewController.renderToUIImage(size: CGSize, itemsToDraw: [MyDrawingItem], transform: CGAffineTransform) + 4313002752 (<compiler-generated>:4313002752)
2 MyApp 0x1a4578 AnyModifier.modified(for:) + 4308649336 (<compiler-generated>:4308649336)
3 MyApp 0x7b4e64 thunk for @escaping @callee_guaranteed (@guaranteed UIGraphicsPDFRendererContext) -> () + 4315008612 (<compiler-generated>:4315008612)
4 UIKitCore 0x1489c0 -[UIGraphicsRenderer runDrawingActions:completionActions:format:error:] + 324
5 UIKitCore 0x14884c -[UIGraphicsRenderer runDrawingActions:completionActions:error:] + 92
6 UIKitCore 0x148778 -[UIGraphicsImageRenderer imageWithActions:] + 184
7 MyApp 0x5cb1c0 closure #1 in MyViewController.renderToUIImage(size: CGSize, itemsToDraw: [MyDrawingItem], transform: CGAffineTransform) + 100 (FileName.swift:100)
8 libswift_Concurrency.dylib 0x60f5c swift::runJobInEstablishedExecutorContext(swift::Job*) + 252
9 libswift_Concurrency.dylib 0x62514 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 144
10 libdispatch.dylib 0x15ec0 _dispatch_root_queue_drain + 392
11 libdispatch.dylib 0x166c4 _dispatch_worker_thread2 + 156
12 libsystem_pthread.dylib 0x3644 _pthread_wqthread + 228
13 libsystem_pthread.dylib 0x1474 start_wqthread + 8
Questions
Is it safe to run UIGraphicsImageRenderer.image on the background thread?
Given that I want to leverage GPU rendering, what are some best practices for rendering images off the main thread while ensuring stability?
Are there alternatives to using UIGraphicsImageRenderer for background rendering that can still take advantage of GPU rendering?
It is particularly interesting that the crash logs indicate the error may be related to UIGraphicsPDFRendererContext (crash log line number 3). It would be very helpful if someone could explain the connection between starting and drawing on a UIGraphicsImageRenderer and UIGraphicsPDFRendererContext.
Any insights or guidance on this issue would be greatly appreciated. Thanks!!!
I work on an iOS app using SwiftUI and SwiftData. I added a computed property to one of my models - Parent - that uses relationship - array of Child models - data and I started getting strange problems. Let me start with models:
@Model
final class Parent {
var name: String
@Relationship(deleteRule: .cascade, inverse: \Child.parent)
var children: [Child]? = []
var streak: Int {
// Yes, I know that's not optimal solution for such counter ;)
guard let children = children?.sorted(using: SortDescriptor(\.date, order: .reverse)) else { return 0 }
var date = Date.now
let calendar = Calendar.current
for (index, child) in children.enumerated() {
if !calendar.isDate(child.date, inSameDayAs: date) {
return index
}
date = calendar.date(byAdding: .day, value: -1, to: date) ?? .now
}
return children.count
}
init(name: String) {
self.name = name
}
}
@Model
final class Child {
var date: Date
@Relationship(deleteRule: .nullify)
var parent: Parent?
init(date: Date, parent: Parent) {
self.date = date
self.parent = parent
}
}
At first everything works as expected. The problem arises once I try to remove one of child from the parent instance. I remove the value from context and save changes without any problems, at least not ones that can be caught by do { } catch. But instead of refreshing UI I get an signal SIGABRT somewhere inside SwiftData internals that points to the line where I'm trying (inside View body) get a child from a Query:
struct LastSevenDaysButtons: View {
@Environment(\.modelContext)
private var modelContext
@Query
private var children: [Child]
private let dates: [Date]
private let parent: Parent
init(for parent: Parent) {
self.parent = parent
var lastSevenDays = [Date]()
let calendar = Calendar.current
let firstDate = calendar.date(byAdding: .day, value: -6, to: calendar.startOfDay(for: .now)) ?? .now
var date = firstDate
while date <= .now {
lastSevenDays.append(date)
date = calendar.date(byAdding: .day, value: 1, to: date) ?? .now
}
dates = lastSevenDays
let parentId = parent.persistentModelID
_children = Query(
filter: #Predicate {
$0.parent?.persistentModelID == parentId && $0.date >= firstDate
},
sort: [SortDescriptor(\Child.date, order: .reverse)],
animation: .default
)
}
var body: some View {
VStack {
HStack(alignment: .top) {
ForEach(dates, id: \.self) { date in
// Here is the last point on stack from my code that I see
let child = children.first { $0.date == date }
Button {
if let child {
modelContext.delete(child)
} else {
modelContext.insert(Child(date: date, parent: parent))
}
do {
try modelContext.save()
} catch {
print("Can't save changes for \(parent.name) on \(date.formatted(date: .abbreviated, time: .omitted)): \(error.localizedDescription)")
}
} label: {
Text("\(date.formatted(date: .abbreviated, time: .omitted))")
.foregroundStyle(child == nil ? .red : .blue)
}
}
}
}
}
}
The LastSevenDaysButtons View is kind of deep in a View hierarchy:
RootView -> ParentList -> ParentListItem -> LastSevenDaysButtons
However once I move insides of ParentList to RootView application works just fine, although I see and warning: === AttributeGraph: cycle detected through attribute 6912 ===.
What could be that I do wrong in here? I believe it must something I'm missing here, but after 2 days of debug, trial and errors, I can't think clearly anymore.
Here is the minimal repro I managed to create: Signal SIGABRT on accessing values from SwiftData query
how to fix swift preview on real device no showing
Question:
I have created a workspace containing a SwiftUI app and two frameworks:
B Framework: Handles UI components
C Framework: Handles service classes
I added a Podfile to manage dependencies. My Podfile is structured as follows:
inhibit_all_warnings!
workspace 'ABC.xcworkspace'
def shared_pods
# Shared pods here
pod 'Alamofire'
end
target 'A' do
use_frameworks!
project 'A/A.xcodeproj'
shared_pods
end
target 'B' do
use_frameworks!
project 'B/B.xcodeproj'
shared_pods
end
target 'C' do
use_frameworks!
project 'C/C.xcodeproj'
shared_pods
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0'
end
end
end
After installing pods and building the project, everything works fine except for Xcode’s SwiftUI Preview, which crashes with the following error:
xcpreviewagent crashed because Alamofire.framework is missing
Question:
How can I resolve this issue and make SwiftUI Previews work without Xcode crashing?
When I was working on my project for Swift Student Challenge, I found an interesting fact regarding camera access. If I create an App project on Xcode, the camera capture works well on it. However, if I copied and pasted the code on an App Playground project on Xcode, it crashed and output several errors. I am wondering why this is happening.
Topic:
Community
SubTopic:
Swift Student Challenge
Tags:
Swift Playground
SwiftUI
Camera
AVFoundation
Hello!
I have a destination navigation which is TabVIew where each tab item is ScrollView. And when scrolling content of any of tab items is underneath navigation bar its background is always hidden. But at the same time tab bar background is toggled depending on scrolling content position.
I expected it would work with TabView the same as with any other view.
Is it supposed to work like that?
VisionOS developers want to modify the color of the button when they detect the eyes focusing on it. May I ask if there are any relevant methods that can be implemented? At present, there is a default highlight color when the eyes focus on the button, but this color is too dim. Not obvious enough, how can I modify it?
thank you!
Is it the default behavior that the standard back swipe (interactivePopGestureRecognizer) does not work when running a designed for iPhone app on an iPad?
To my knowledge, all apps behave this way.
Are there any workarounds?
I opened a feedback ticket (FB16508762) but maybe someone in the community already found a workaround while the feedback reaches the maintainers.
When I put a Button inside a ScrollView, the tap animation stops working reliably and works only when the user taps and holds the button for a short time. The reasons, I believe is related to the fact that isPressed of configuration does not change and the default button styles use it to animate the tap.
import SwiftUI
struct DebuggingButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.onChange(of: configuration.isPressed, { oldValue, newValue in
print("Is pressed: \(oldValue) -> \(newValue)")
})
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Buttons inside scroll view respond to taps as expected, however isPessed value of the configuration do not change unless the user press and hold it. Try to press the promiment button quickly or use the debug button and observe the console log.")
ScrollView {
VStack {
Button("Button Inside ScrollView") {
print("Button tapped")
}
.buttonStyle(.borderedProminent)
Button("Button Inside ScrollView (printing isPressed)") {
print("Button tapped")
}
.buttonStyle(DebuggingButtonStyle())
}
}
.border(FillShapeStyle(), width: 2)
Spacer()
Text("For reference, here is a button outside of a ScrollView. Tap the promiment button to observe how the button is expected to animate in respnse to a press.")
VStack {
Button("Button Outside ScrollView") {
print("Button tapped")
}
.buttonStyle(.borderedProminent)
Button("Button Outside ScrollView (printing isPressed)") {
print("Button tapped")
}
.buttonStyle(DebuggingButtonStyle())
}
}
.padding()
}
}
My usage of TextField.focused() works fine in Xcode 14.3.1 but is broken as of Xcode 15. I first noticed it in the second beta and it's still broken as of the 4th beta.
Feedback / OpenRadar # FB12432084
import SwiftUI
struct ContentView: View {
@State private var text = ""
@FocusState var isFocused: Bool
var body: some View {
ScrollView {
TextField("Test", text: $text)
.textFieldStyle(.roundedBorder)
.focused($isFocused)
Text("Text Field Is Focused: \(isFocused.description)")
}
}
}
HStack{
FormLable(text: NSLocalizedString("Color", comment: ""))
Spacer()
Image(systemName: "circle.fill")
.font(.system(size: AppFontSize.baseSize.size() * 1.2, weight: .medium))
.foregroundColor(color)
.overlay(ColorPicker("Color", selection: $color).labelsHidden().opacity(0.015))
}
This is how I use the color picker. I used the same code in two different apps, and the color picker appeared in one app but not in the other. By the way, I upgraded Xcode to the latest version.
Hello.
I have a scenario where a hover effect is being shown for a button that is disabled. Usually this doesn't happen but when you wrap the button in a Menu it doesn't work properly.
Here is some example code:
struct ContentView: View {
var body: some View {
NavigationStack {
Color.green
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Menu("Menu") {
Button("Disabled Button") {}
.disabled(true)
.hoverEffectDisabled() // This doesn't work.
Button("Enabled Button") {}
}
}
}
}
}
}
And here is what it looks like:
This looks like a SwiftUI bug. Any help is appreciated, thank you!
I'm getting the following error in my SwiftUI code:
"Main actor-isolated property 'avatarImage' can not be referenced from a Sendable closure"
I don't understand how to fix it.
This happens in the following code:
You can copy-paste this into an empty project and make sure to have Swift 6 enabled under the Build Settings > Swift Language Version
import PhotosUI
import SwiftUI
public struct ContentView: View {
@State private var avatarItem: PhotosPickerItem?
@State private var avatarImage: Image?
@State private var avatarData: Data?
public var body: some View {
VStack(spacing: 30) {
VStack(alignment: .center) {
PhotosPicker(selection: $avatarItem, matching: .images) {
if let avatarImage {
avatarImage
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.foregroundColor(.gray)
.background(.white)
.clipShape(Circle())
.opacity(0.75)
.overlay {
Image(systemName: "pencil")
.font(.title)
.shadow(radius: 5)
}
} else {
Image(systemName: "person.circle.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 100, height: 100)
.foregroundColor(.gray)
.background(.white)
.clipShape(Circle())
.opacity(0.75)
.overlay {
Image(systemName: "pencil")
.font(.title)
.shadow(radius: 5)
}
}
}
}
}
.onChange(of: avatarItem) {
Task {
if let data = try? await avatarItem?.loadTransferable(
type: Data.self
) {
if let processed = processImage(data: data) {
avatarImage = processed.image
avatarData = processed.data
} else {
}
}
}
}
}
private func processImage(data: Data) -> (image: Image?, data: Data?)? {
guard let uiImage = UIImage(data: data)?.preparingForDisplay() else {
return nil
}
// Check original size
let sizeInMB = Double(data.count) / (1024 * 1024)
// If image is larger than 1MB, compress it
if sizeInMB > 1.0 {
guard let compressedData = uiImage.compress() else { return nil }
return (Image(uiImage: uiImage), compressedData)
}
return (Image(uiImage: uiImage), data)
}
}
#Preview {
ContentView()
}
public extension UIImage {
func compress(to maxSizeInMB: Double = 1.0) -> Data? {
let maxSizeInBytes = Int(
maxSizeInMB * 1024 * 1024
) // Convert MB to bytes
var compression: CGFloat = 1.0
let step: CGFloat = 0.1
var imageData = jpegData(compressionQuality: compression)
while (imageData?.count ?? 0) > maxSizeInBytes, compression > 0 {
compression -= step
imageData = jpegData(compressionQuality: compression)
}
return imageData
}
}
❌ Could not find email_ai.py in the app bundle. Available files: []
The error above is what I’m encountering.
I’ve placed the referenced file both in the project directory and inside the app. However, every time I remove and reinsert the file into the folder within the app, it prompts me to designate the targets—I select all, but this doesn’t resolve the issue.
I’m unsure how to properly reference the file so that it is recognised and included in the bundle. Any guidance would be greatly appreciated.
this is my build phase:
#!/bin/sh
set -x # Prints each command before running it (for debugging)
pwd # Shows the current working directory
echo "$SRCROOT" # Shows what Xcode thinks is the project root
ls -l "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts" # Lists files in the script folder
export PYTHONPATH="/Users/caesar/.pyenv/versions/3.11.6/bin"
/Users/caesar/.pyenv/versions/3.11.6/bin/python3 "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts/email_ai.py"
echo "Script completed."
As you can see in the screenshot, the verification popups that appear when making a StoreKit purchase cut off the buttons. When typing the code into the input field, the window will also flicker and stutter with random view refreshes. Is this something I can configure/change? It's not a very pleasant experience for making an in app purchase.
Given a sheet with [.medium] detents, that contains a native ColorPicker in SwiftUI:
struct SheetView: View {
@State var color: Color = .white
var body: some View {
ColorPicker(
"Color",
selection: $color,
supportsOpacity: false
)
.padding()
}
}
struct ContentView: View {
@State var isSheetOpen = false
var body: some View {
Button("Open Sheet") {
isSheetOpen = true
}
.sheet(isPresented: $isSheetOpen) {
SheetView()
.presentationDetents([.medium])
}
}
}
When I tap the ColorPicker's color indicator button, it presents the color picker sheet with a layout glitch.
During the color picker presentation animation, the original sheet (SheetView) is rapidly pushed up and back down.
It is a wild guess but I think it has to do something with keyboard avoidance.
Unfortunately, this makes it impossible to use the picker in my app....