I have a SwiftUI view that is being passed a binding from a parent view. I would like to preview the subview, but can't. I tried .constant and a @Model object directly. Both ways crash the preview.
Any idea on how I can get this to work properly?
@Model
class FamilyMember: Identifiable {
@Attribute(.unique) var id: String { name }
var name = ""
init(name: String = "") {
self.name = name
}
}
struct MemberView: View {
@Bindable var member: FamilyMember
var body: some View {
Text(member.name)
}
}
#Preview {
MemberView(member: FamilyMember(name: "Family member"))
}
#Preview {
MemberView(member: .constant(FamilyMember(name: "Family member")))
}
Xcode Previews
RSS for tagCreate an app UI and configure almost everything your users see using Xcode Previews.
Posts under Xcode Previews tag
153 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have a Mac app in Xcode using SwiftUI.
Recently I noticed the Xcode's previews had become very sluggish, and after some sleuthing I discovered that was because when the previews were running, it would spawn a new instance of the app in the background for every keystroke, and never quits any of these instances.
Here's a video where you can see the problem: https://static.squares.tv/Xcode%20Spawning%20720p.mov
It's a document-based app where I'm doing a lot of Metal rendering, using different audio and video frameworks and extensions with custom networking so it's possible something is blocking the app's ability to quit easily.
How do I troubleshoot this problem to figure out exactly what is preventing Xcode from operating cleanly here?
Summary
When trying to display SwiftUI previews, building the previews may fail with the following error:
Linking failed: linker command failed with exit code 1 (use -v to see invocation)
ld: warning: search path '/Applications/Xcode.app/Contents/SharedFrameworks-iphonesimulator' not found
ld: warning: Could not find or use auto-linked framework 'CoreAudioTypes': framework 'CoreAudioTypes' not found
Note that may app does not use CoreAudioTypes.
Observation
This issue seems to occur when two conditions are met:
The SwiftUI view must be located in a Swift Package
Somewhere in either the View or the #Preview a type from another package has to be used.
Say I have to packages one named Model-package and one named UI-Package. The UI-Package depends on the Model-Package. If I have a SwiftUI view in the UI-Package that uses a type of the Model-Package either in the View itself or in the #Preview, then the described error occurs. If I have a View in the UI-package that does not use a type of the Model-Package anywhere in its View or #Preview then the SwiftUI Preview builds and renders successful.
I created a bug report: FB13033812
The Xcode Canvas Simulator (for Xcode 14 and even 15 ..beta 6) cause multiple springboard and diagnosticd processes to run at nearly 100% CPU , cause the MacBook M1 to heat. This happens every time.
This is usually triggered after the Canvas show an error which live previewing the code as I edit it.
I have tried clearing the derived data but it doesn't seem to help. This happens with all projects. I am unable to use live previews because of this issue.
The are often other processes with the string Poster in them. Like PhotosPosterProvider , CollectionsPoster , ExtragalacticPoster running high on usage at the same time.
A similar request was posted last year and the response was to request a generated report.
This is unacceptable; we cannot preview our app reliably because we have to use a hybrid build because you insist on releasing framework updates piecemeal and NEVER back-porting them. So no, "generating a report" for you to fix whatever the delay is, will not work for us.
PLEASE..
Give us a way to increase this timeout value in the project. You put us into this mess, give us a way to get out of it without having to wait on Apple engineers to "analyze" it.
XCode Previews do not work when defined in a Swift Package in XCode 15 beta 6. The following error will be returned when trying to show a SwiftUI Preview:
FailedToInstallAppError: Failed to install ”XCPreviewAgent.app”
Could not install the preview host ”XCPreviewAgent.app” on iPhone 14 Pro
...
HumanReadableNSError: Simulator device returned an error for the requested operation.
Ensure your bundle contains a valid CFBundleShortVersionString.
As far as I know, a Swift Package doesn't need a CFBundleShortVersionString declared? Am I missing something?
Replicate Error
To replicate the error, simply create a new SPM package from XCode, and create a Preview:
struct Preview: PreviewProvider {
static var previews: some View {
Group {
Text("Hello")
}
}
}
Does anyone know of any workaround this issue?
I am having an issue when previewing a UIKit ViewController. I am developing my app inside Pods framework which then I import and use in scene/app delegate. I tried to use UIKit to have SwiftUI previews. I conformed to UIViewRepresentable protocol and made a struct that conforms to PreviewProvider where I returned the current controller as some View. I have many external dependencies like Moya, Alamofire, SnapKit...
I am building my components in Pods project. Which I import than into scene/app delegate to start the app.
I am getting the error: "Cannot preview in this file; Unexpected error occurred". I went online and found some people saying that I need to disable Automatically Refresh Canvas setting. But it still doesn't work. I am then getting an error: "Cannot preview in this file; Update failed". I attached a file with a generated report from the error. I also cleaned the build folder and restarted my Mac. I am using Macbook Pro M2.
If I run UIKit previews in a new project it works. But I need it to be able to run in my current project.
https://www.notion.so/Xcode-Previews-UIKit-Error-Report-ba5ec69080f34cb09c6f93c6cd0131d7?pvs=4
Hi guys,
I am migrating my widgets to iOS 17 and because I already manage my layout margins, I just want to disable to new built-in widget content margins.
I did it by using ".contentMarginsDisabled()" on the WidgetConfiguration and it works fine at run time.
WIDGET CODE
struct MyWidget: Widget {
let kind: String = "MyWidget"
var body: some WidgetConfiguration {
return IntentConfiguration(kind: kind, intent: MyWidgetIntent.self, provider: WidgetProvider<MyWidgetIntent>()) { entry in
WidgetView<MyWidgetIntent>(entry: entry)
}
.configurationDisplayName("My Widget")
.supportedFamilies([WidgetFamily.systemMedium])
.contentMarginsDisabled() // <-- HERE
}
}
RESULT
Nevertheless, when previewing the WidgetView in a WidgetPreviewContext I didn't find anyway to disable the content margins (because manipulating directly the view and not a WidgetConfiguration).
PREVIEW CODE
struct MyWidget_Previews: PreviewProvider {
static var previews: some View {
WidgetView<MyWidgetIntent>(entry: WidgetEntry<MyWidgetIntent>())
// .padding(-16) Need to add this negative padding to disable margin
.previewContext(
WidgetPreviewContext(family: .systemMedium))
}
}
Do you know how to disable the content margins for widget preview?
If I have the code below and do the following with preview on:
Choose one of the TextEditors and start typing: works
Go to another one. Start typing, the text shows only in the first one you chose.
Try to delete the text while on the second (or third, or fourth) and you can't.
Try to delete the text in the first one. It works. >.<
If you check the preview console, you will see that the first variable is used forever.
Is anyone having the same problem? So annoying having to run everything every single time.
I'm running the Xcode on Sonoma 14.0.
import SwiftUI
struct TextStruct {
var text1: String = "text1"
var text2: String = "text2"
}
struct TextSummaryEditorView: View {
@State private var textForSummary: String = "textForSummary"
@State private var boomshakalaka: String = "boomshakalaka"
@State private var textstruct: TextStruct = TextStruct(text1: "boo1", text2: "boo2")
var body: some View {
VStack {
VStack {
Text(textForSummary)
TextEditor(text: $textForSummary)
.textFieldStyle(PlainTextFieldStyle())
.font(.system(size: Config.defaultFontSize))
.padding()
.background(Color("background").opacity(0.9))
.lineSpacing(10)
.zIndex(1)
.multilineTextAlignment(.leading)
Text(boomshakalaka)
TextEditor(text: $boomshakalaka)
.textFieldStyle(PlainTextFieldStyle())
.font(.system(size: Config.defaultFontSize))
.padding()
.background(Color("background").opacity(0.9))
.zIndex(0.9)
Text(textstruct.text1)
TextEditor(text: $textstruct.text1)
.textFieldStyle(PlainTextFieldStyle())
.font(.system(size: Config.defaultFontSize))
.padding()
.background(Color("background").opacity(0.9))
.lineSpacing(10)
.zIndex(1)
.multilineTextAlignment(.leading)
Text(textstruct.text2)
TextEditor(text: $textstruct.text2)
.textFieldStyle(PlainTextFieldStyle())
.font(.system(size: Config.defaultFontSize))
.padding()
.background(Color("background").opacity(0.9))
.zIndex(0.9)
}
.cornerRadius(Config.radioL)
.onChange(of: boomshakalaka) {
print(boomshakalaka)
}
Text("Button")
}
}
}
struct TextSummaryEditorView_Previews: PreviewProvider {
static var previews: some View {
VStack {
TextSummaryEditorView()
}
.padding()
.background(Color("background").opacity(0.4))
}
}```
Xcode: 14.3
Cocopods: 1.11.3
SwiftUI file Previews error for Xcode 14.3 , and my project is written in OC and Swift
The following is the detailed error information, what may be the cause?
Thanks a lot!
= PREVIEW UPDATE ERROR:
HumanReadableSwiftError
ProviderError: ProviderError: noPreviewInfos(runDestination: Simulator - iOS 16.4 | iphonesimulator | arm64 | iPhone 14 Pro Max | no proxy, thunkConfiguration: <IDEBuildOperationConfiguration: 0x6000cc5510a0; buildParameters=<IDEBuildParameters:0x600070e4a580:action=build:command=<IDEConcretePrimitiveSchemeCommand:0x60000629abb0:Run>:config=Debug:dest=iPhone 14 Pro Max:arch=arm64:workspaceArena=<IDEWorkspaceArenaSnapshot: 0x60008415fe00>:
overridingProperties=(
{ // Preview overrides (immutable)
DSTROOT = 【𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝗦𝘁𝗿𝗶𝗻𝗴:/Users/wj/Library/Developer/Xcode/DerivedData/MyApp-gljivierkfnnqydoswlgudwodyeg/Build/Intermediates.noindex/Previews/MyApp/ReleaseProducts】
ENABLE_PREVIEWS = 【YES】
OBJROOT = 【𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝗦𝘁𝗿𝗶𝗻𝗴:/Users/wj/Library/Developer/Xcode/DerivedData/MyApp-gljivierkfnnqydoswlgudwodyeg/Build/Intermediates.noindex/Previews/MyApp/Intermediates.noindex】
SYMROOT = 【𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝗦𝘁𝗿𝗶𝗻𝗴:/Users/wj/Library/Developer/Xcode/DerivedData/MyApp-gljivierkfnnqydoswlgudwodyeg/Build/Intermediates.noindex/Previews/MyApp/Products】
},
):
collectBuildTimeStatistics=NO
collectTimelineMetrics=NO>:executionEnvironment=<IDEExecutionEnvironment: 0x2cf4c0550>:singleFileToBuild=(null):buildLog=(null):parallelizeBuildables=YES:dontActuallyRunCommands=NO:buildImplicitDependencies=YES:skipDependencies=NO:restorePersistedBuildResults=YES:enableIndexBuildArena=NO:buildables=(
"<Xcode3TargetProduct:0x60010c4472a0:MyApp.app blueprint:<Xcode3Target:0x2ee0b7860:MyApp>>"
):subsetOfBuildables=(null):buildDescriptionID=(null):scheme=<IDEScheme:0x461aeff20:'MyApp'>:schemeTask=BuildAndCommand:clientInfo=(null)>, blueprintName: TaskActivity, sourceFilePath: /Users/wj/Desktop/international/MyApp/DependencesLib/MyAppLib/TaskActivity/TaskActivity/View/InviteFriend/InviteFriendView.swift, thunkVariantSuffix: __XCPREVIEW_THUNKSUFFIX__)
Hello,
In WidgetKit, I have to write multiple #Preview macros for each family the widget supports. So is there any better way to write the #Preview?
(Although I can use the legacy PreviewProvider but it does not support timeline to test transition animation.)
#import WidgetKit
#import SwiftUI
struct DailyCaffeineWidget: Widget {
...
}
@available(iOS 17.0, *)
#Preview("Inline", as: .accessoryInline) {
DailyCaffeineWidget()
} timelineProvider: {
previewTimelineProvider()
}
@available(iOS 17.0, *)
#Preview("Circular", as: .accessoryCircular) {
DailyCaffeineWidget()
} timelineProvider: {
previewTimelineProvider()
}
@available(iOS 17.0, *)
#Preview("Rectangular", as: .accessoryRectangular) {
DailyCaffeineWidget()
} timelineProvider: {
previewTimelineProvider()
}
@available(iOS 17.0, *)
#Preview("Small", as: .systemSmall) {
DailyCaffeineWidget()
} timelineProvider: {
previewTimelineProvider()
}
@available(iOS 17.0, *)
#Preview("Medium", as: .systemMedium) {
DailyCaffeineWidget()
} timelineProvider: {
previewTimelineProvider()
}
...
Following article Creating a widget extension on developer.apple.com (https://developer.apple.com/documentation/widgetkit/creating-a-widget-extension) I encountered a problem with XCode preview: it shows an error with message
| RemoteHumanReadableError: Failed to launch agent
| No plugin is registered to launch the process type widgetExtension.
Can someone help me?
macOS 13.4
XCode 14.3.1
Hiya,
I am having issues trying to use previews in the xcode 15 beta, i am using an M2 macbook air with 8gb of ram.
I am using MacOS Sonoma and iOS 17.0 Beta 1 and am struggling using previews, the base simulator works but no previews.
I am not receiving any error so am very confused.
Any help would be majorly appreciated.
Thanks,
Gus
I am not able to present the preview of xcode 15,
I am having the error message "Cannot preview in this file" "Syntax error" but I have no error in xcode.
Hello!
I can't preview the SwiftUI views of watchOS target in Xcode 15 beta 1, when the containing iOS app has a SPM dependency. Reproducing steps:
Create a new watchOS app project (with a companion iOS app) in Xcode 15.
Both iOS and watchOS ContentView can be previewed at this step.
Add a Swift package to the iOS target (the package should be an iOS-specific package, not a watchOS one, for example, https://github.com/siteline/SwiftUI-Introspect)
After you add the static library to iOS target, the watchOS preview no longer work anymore.
If you check the error message, you can find the Xcode preview attempt to build the iOS package against watchOS SDK.
Greetings...
I am trying to use @Namespace for my matchedGeometryEffect use case.
prior to Xcode 15 beta the following code worked just fine:
struct ChapterItem_Previews: PreviewProvider {
@Namespace static var namespace
static var previews: some View {
ChapterItem(namespace: namespace, show: .constant(true))
}
}
However trying to do the same within the new Xcode 15 beta #Preview Macro
#Preview {
@Namespace var namespace
ChapterItem(namespace: namespace, show: .constant(true))
}
produces the following error message:
Ambiguous use of 'Preview(_:traits:body:)'
May I kindly get assistance on the proper way I can get this to work in Xcode 15 beta?
Please be as detail as you can since I'm still new to swiftUI as well Thank You.
When using Xcode's Preview or Simulator, I noticed that my M2 Air will overheat. This hasn't happened before in Ventura or Xcode 14.
Recently have been working on this project just fine... had an app throw a warning for some malware called InstallCore. Removed the malware and now I am getting this on every preview, regardless of the device preview type.
I've tried clearing derived data, cache, etc. No dice.
Could not install the preview host "AppName.app" on iPhone 14 Pro Max: Failed to get parent identifier for BUNDLEIDENTIFIER.
Hello,
I've created multiple Entity in CoreData, that has a relationship to one another. However, I'm unable to create @discardableResult to use in SwiftUI preview.
/// Entity data for use with canvas previews.
static var preview: Entity1 {
let entities1 = Entity1.makePreviews(count: 1)
return entities1[0]
}
@discardableResult
static func makePreviews(count: Int) -> [Entity1] {
var contents = [Entity1]()
let viewContext = PersistenceController.preview.container.viewContext
let persistenceController = PersistenceController.shared
for index in 0..<count {
let entities1 = Entity1(context: viewContext)
entities1.id = UUID()
entities1.title = "Amazing day!"
let photo = Photo(context: viewContext)
let imageData = UIImage(named: "Golden Temple")?.jpegData(compressionQuality: 1) ?? Data()
photo.linkedToJournal = journal
let thumbnail = Thumbnail(context: viewContext)
let thumbnailData = persistenceController.thumbnail(with: imageData)?.jpegData(compressionQuality: 1)
thumbnail.data = thumbnailData
thumbnail.photo = photo
let photoDataObject = PhotoData(context: viewContext)
photoDataObject.data = imageData
photoDataObject.photo = photo
contents.append(entities1)
}
return contents
}
You may also try to use the sample code from https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users to build a SwiftUI Preview.
Appreciate if you could suggest how to build a SwiftUI preview as it saves a lot of development effort and time. Thank you very much!
Hey guys, anybody knows how to fix issues with the keyboard on Xcode in preview mode? it used to work well for me but has now stopped working, see details.
Problem statement: Cannot use the keyboard in previews. For example, typing in a textfield does nothing. Everything works well in simulator.
Environment: macOS Monterey 12.6
Xcode 14.1
Thanks in advance for your input.