Hello! 👋
In previous versions of Xcode I was used to make something like this:
struct MyView_Previews: PreviewProvider {
static var previews: some View {
MyView()
.previewInterfaceOrientation(.landscapeLeft)
}
}
So I don't have to change the Device Settings in the Canvas.
Now, with Xcode 15, I couldn't manage to do the same.
#Preview {
MyView()
.previewInterfaceOrientation(.landscapeLeft)
}
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
Hi,
In Xcode 15 is command click on an item in the preview canvas feature removed ? it doesn't work for me ?
Kindest Regards
I'm trying to get rid of the auto-padding added recently by iOS 17, and I found out that you can use the WidgetConfigurations properly with the new Preview Macro, but I'm having trouble getting it to work, and some help would be much appreciated.
Here's my code:
struct ChartEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationIntent
...
static func getSampleEntry() -> ChartEntry {
let sample = ChartEntry(date: Date(), configuration: WidgetUtils.getSampleConfiguration())
return sample
}
}
struct PreviewTimelineProvider: TimelineProvider {
typealias Entry = ChartEntry
func placeholder(in context: Context) -> ChartEntry {
ChartEntry.getSampleEntry()
}
func getSnapshot(in context: Context, completion: @escaping (ChartEntry) -> Void) {
completion(ChartEntry.getSampleEntry())
}
func getTimeline(in context: Context, completion: @escaping (Timeline<ChartEntry>) -> Void) {
var entries: [ChartEntry] = []
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = ChartEntry(date: entryDate, configuration: WidgetUtils.getSampleConfiguration())
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct DailyHoursOfSunshine: Identifiable {
let id = UUID()
var date: Date
var hoursOfSunshine: Double
init(date: Date, hoursOfSunshine: Double) {
self.date = date
self.hoursOfSunshine = hoursOfSunshine
}
}
var data = [
DailyHoursOfSunshine(date: Date(), hoursOfSunshine: 0), // Sunday
DailyHoursOfSunshine(date: Date().addingTimeInterval(86400), hoursOfSunshine: 60), // Monday
DailyHoursOfSunshine(date: Date().addingTimeInterval(2 * 86400), hoursOfSunshine: 50), // Tuesday
DailyHoursOfSunshine(date: Date().addingTimeInterval(3 * 86400), hoursOfSunshine: 72), // Wednesday
DailyHoursOfSunshine(date: Date().addingTimeInterval(4 * 86400), hoursOfSunshine: 88), // Thursday
DailyHoursOfSunshine(date: Date().addingTimeInterval(5 * 86400), hoursOfSunshine: 70), // Friday
DailyHoursOfSunshine(date: Date().addingTimeInterval(6 * 86400), hoursOfSunshine: 120) // Saturday
]
struct ChartSmallView: View {
var entry: ChartEntry
var body: some View {
VStack {
Spacer()
VStack(alignment: .leading, spacing: 0) {
Chart(data) {
AreaMark(
x: .value("Week", $0.date),
y: .value("Hours of Sunshine", $0.hoursOfSunshine)
)
.alignsMarkStylesWithPlotArea()
}
.foregroundStyle(
.linearGradient (
colors: [.blue, .clear],
startPoint: .top,
endPoint: .bottom
)
)
.chartXAxis(.hidden)
.chartYAxis(.hidden)
.chartLegend(.hidden)
.padding([.horizontal], 3)
}
Spacer()
}
.frame(maxWidth: .infinity)
}
}
#Preview("Small", as: .systemSmall) {
ChartWidget()
} timelineProvider: {
PreviewTimelineProvider()
}
NOTE: There's nothing much on my ChartWidget struct, just the configuration to disable the margins and declare the preferred size and calling the ChartSmallView struct, I just didn't copy it here because it is in another file and I'm a little busy to go out excluding sensible information.
I would actually prefer to call just ChartSmallView on my preview, but then I wouldn't have access to the configuration that disables the awful contextualized margins.
The code compiles just fine, but when the preview tries to build it, the following error happens:
== PREVIEW UPDATE ERROR:
CompileDylibError: Failed to build ChartSmallView.swift
Compiling failed: cannot convert value of type 'PreviewTimelineProvider' to closure result type 'any View'
@__swiftmacro_63MyWidgetExtension_PreviewReplacement_ChartSmallView_133_77BD2C8074131F1FDF53BC08606762A7Ll0F0fMf_.swift
------------------------------
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, xrOS 1.0, *)
struct $s63MyWidgetExtension_PreviewReplacement_ChartSmallView_133_77BD2C8074131F1FDF53BC08606762A7Ll0F0fMf_15PreviewRegistryfMu_: DeveloperToolsSupport.PreviewRegistry {
static let fileID: String = "MyWidgetExtension_PreviewReplacement_ChartSmallView_1/ChartSmallView.1.preview-thunk.swift"
static let line: Int = 125
static let column: Int = 1
static func makePreview() throws -> DeveloperToolsSupport.Preview {
DeveloperToolsSupport.Preview("Small", as: .systemSmall) {
ChartWidget()
} timelineProvider: {
PreviewTimelineProvider()
}
}
}
------------------------------
/.../MyWidgetExtension.build/Objects-normal/x86_64/ChartSmallView.1.preview-thunk.swift:137:13: error: cannot convert value of type 'PreviewTimelineProvider' to closure result type 'any View'
PreviewTimelineProvider()
^~~~~~~~~~~~~~~~~~~~~~~~~
as! any View
I have also attempted to use the Preview Macro in the following way:
#Preview("Small", as: .systemSmall) {
ChartWidget()
} timeline: {
ChartEntry.getSampleEntry()
}
But achieved the same result.
If anyone has any idea of what I'm doing wrong, I would appreciate the help. I couldn't find much material online to help me here
After update my Xcode to 15.0, my SwitUI views stoped to open on Preview Canvas
It runs on Simulator, but I can't previews the UI.
Can someone help or give some tips where should I look for?
SwiftUI preview hangs on "Preparing iPhone Simulator for Previews". Also simulator hangs when trying to build and run. This occurred after I installed iOS 17 simulator. I tried reverting back to an iOS 16 version of the simulator, but haven't figured out how to do that. Build and run to an iPhone device works fine. Any ideas would be appreciated. Thanks.
I am Unable To Load LivePreview On My Xcode But My Simulator is Working Fine Can Someone Help me With That .
Now that live previews are available in UIKit (source: https://developer.apple.com/wwdc23/10252)
I was wondering how to get a UIViewController from Objective-C. The Swift macro looks like this:
#Preview {
var controller = SomeViewController()
return controller;
}
Is there a way to get a live preview for UIViewControllers/UIViews written in Objective-C (other than wrapping it as a child view controller in an empty swift view controller)?
In Xcode 15 Live Previews are available for UIKit view controllers and views. However I noticed they do not work if the deployment target is < 17.0.
If I try to make a live preview for a view controller like so:
#Preview {
let someVC = ViewController()
return someVC
}
It doesn't load.
The error is described below:
== PREVIEW UPDATE ERROR:
CompileDylibError: Failed to build ASwiftViewController.swift
Compiling failed: module 'SwiftUI' has no member named 'VStack'
If I raise the deployment target to iOS 17 it starts working.
I have a Mac Catalyst app. When using "Live Previews" in Xcode 15 for a view controller of mine the live preview renders at a gigantic size in the Preview.
This view controller is only ever presented as a "sheet" on Mac at a fixed size so ideally I'd like to be able to specify the "window size" for the preview environment.
Is there a way to do this? Thanks in advance.
I have a UIViewController subclass I'm using in Mac Catalyst. This view controller is only ever presented as a sheet. When I try to make a live preview for it the preview is displayed a gigantic size (not the sheet's actual size at runtime). I made a separate thread about this: https://developer.apple.com/forums/thread/738641
In order to be able to preview the view controller for Mac Catalyst at the desired size I figured I'd present it on another view controller.
#Preview {
let wrapperVC = WrapperViewController()
return wrapperVC
}
//In WrapperViewController
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
if (firstViewDidAppear)
{
firstViewDidAppear = false
view.backgroundColor = UIColor.yellow
let realVC = ActualVCIWantToPreview()
realVC.modalPresentationStyle = .formSheet
present(realVC, animated: false);
}
}
But that's not working. However if I change the device from Mac to iPad it does work so it appears modal presentations aren't working for Live Previews on Mac Catalyst (unless I'm doing something wrong but Xcode is reporting no errors it just isn't showing my presented view controller).
I have recently created a very simple Swift Macro that I can attach to a view that will generate the boilerplate we have in the project for passing in the view model instance.
@TPView<CompanyProfileViewModel>
struct CompanyProfileView: View {
...
// expanded code
private (set) var viewModel: CompanyProfileViewModel
init(viewModel: CompanyProfileViewModel) {
self.viewModel = viewModel
}
}
However the issue I'm running into is that whilst this init method is accessible in most of the project, when I try to use it in a #Preview block I get errors:
#Preview("Default") {
CompanyProfileView(viewModel: .mock())
.previewLayout(.fixed(width: 380, height: 2000))
}
Based on the top error it seems like the #Preview block isn't able to see the generated init method. I could go back to just using the standard preview code that doesn't using #Preview, but that seems like I'm taking a step forward and a step back with making the code less verbose.
Any suggestions on how to get this working? This seems like a bug to me.
MacBook Air m2 with Sonoma 14 and Xcode 15.
When running simulator or preview of IOS app, the laptop rapidly heats to an alarming degree. According to activity monitor there is not excessive CPU.
This is the IOS 17 version. I saw a suggestion to try 16.4. But in Xcode 15 I cannot see the pathway to change the IOS version. You can create a simulator for it, but Xcode still only sees IOS 17.
When I set the preview mode to selectable the app is restarted at the home screen. However, I want really to look at a secondary screen reached by clicking a navigation link icon on the main screen. In this mode clicking the icon selects it but doesn't activate it. This seems like a catch 22. How could I get to the secondary screen in selectable mode? Is there a key/click combination that does a real click in selectable mode so I can get to it?
Hello, everything worked fine when I packaged my APP with the old version of Xcode, but I started reporting this error when I archived the package with Xcode15. I hope to get your help, thank you.
error:
Build target App of project App with configuration Release
PhaseScriptExecution [CP]\ Embed\ Pods\ Frameworks /Users/wang/Library/Developer/Xcode/DerivedData/App-dcarpmhimruyzxfuqacwgyqbpwsy/Build/Intermediates.noindex/ArchiveIntermediates/App/IntermediateBuildFilesPath/App.build/Release-iphoneos/App.build/Script-9592DBEFFC6D2A0C8D5DEB22.sh (in target 'App' from project 'App')
cd /Users/wang/Documents/new-bn-app/bn-app/ios/App
/bin/sh -c /Users/wang/Library/Developer/Xcode/DerivedData/App-dcarpmhimruyzxfuqacwgyqbpwsy/Build/Intermediates.noindex/ArchiveIntermediates/App/IntermediateBuildFilesPath/App.build/Release-iphoneos/App.build/Script-9592DBEFFC6D2A0C8D5DEB22.sh
mkdir -p /Users/wang/Library/Developer/Xcode/DerivedData/App-dcarpmhimruyzxfuqacwgyqbpwsy/Build/Intermediates.noindex/ArchiveIntermediates/App/BuildProductsPath/Release-iphoneos/App.app/Frameworks
Symlinked...
rsync --delete -av --filter P .*.?????? --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "../../../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Capacitor.framework" "/Users/wang/Library/Developer/Xcode/DerivedData/App-dcarpmhimruyzxfuqacwgyqbpwsy/Build/Intermediates.noindex/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App.app/Frameworks"
building file list ... rsync: link_stat "/Users/wang/Documents/new-bn-app/bn-app/ios/App/../../../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Capacitor.framework" failed: No such file or directory (2)
done
sent 29 bytes received 20 bytes 98.00 bytes/sec
total size is 0 speedup is 0.00
rsync error: some files could not be transferred (code 23) at /AppleInternal/Library/BuildRoots/d9889869-120b-11ee-b796-7a03568b17ac/Library/Caches/com.apple.xbs/Sources/rsync/rsync/main.c(996) [sender=2.6.9]
Command PhaseScriptExecution failed with a nonzero exit code
I'm using Xcode 15 15A240d
Similarly to https://developer.apple.com/forums/thread/731732 when I try to run the Xcode previews for watchOS views in a watchOS target I get compilation errors from UIKit code.
This is only valid for Xcode Previews. Building the code normally / Run it on simulator or device works.
I don't understand why Xcode attempts to build iOS code.
my scheme does include the host app for the watch
I made a duplicate of that scheme by unchecking the host app and that makes previews work again.
I'm not sure this is the intended behavior. I double checked and this was not the case with Xcode 14.3.1 I could run the initial target without issues on Xcode previews.
Do you experience the same issue? is this a problem with my scheme settings or an Xcode bug?
Prior to updating to MacOS 14, the Preview code would read main bundle files listed in Preview Content when the target was MacOS. Now, the files are not read.
When the target is iPadOS, the files are read and the preview works.
Does anyone know what is happening? I suspect that this has something to do with the App Sandbox security features.
I am trying to create a new project in XCode, and my preview won't load. I have deleted and reinstalled, deleted the cache, developer data, etc., and nothing works:
Hi,
Having various problems with Xcode. Finally got it to load the runtimes and now when I try to preview, either with the old method or #Preview, the preview panel icon spins and the folder view refreshes several times until Xcode finally crashes with a SIGABRT.
I've sent feedback, but not sure if I will hear back. I've tried with public 15.0, 15.0.1 RC and 15.1 Beta. All the same.
The status bar at the top changes between 'Packages | Fetching' and 'Indexing | Processing Files', while the Folder list on the left keeps refreshing. About 10 refreshes later and Xcode crashes.
Running directly in the simulator works, although it does take a long time to start after the app has loaded.
This is with iOS 17.0 as the target or with 16.0.
I cleared out all the previews with:
xcrun simctl --set previews delete all
Which saved some space but didn't help.
Thanks, Darren
It seem that Xcode preview compiler fail correctly parse generic and produce a "Failed to build" error:
Proposed example:
^^^^^^^^^^^^^^^^^^^^^^^^^^^
import CoreBluetooth
import SwiftUI
/// Working in preview
/*
struct InitialView<S>: View where S: StringProtocol {
var body: some View {
NestedView()
}
struct NestedView: View {
var body: some View {
Text("Hello")
}
}
}
struct WorkingView: View {
var body: some View {
InitialView<String>()
}
}
*/
/// Not working in preview
struct NotWorking: View {
var body: some View {
InitialView<String>()
}
struct InitialView<S>: View where S: StringProtocol {
var body: some View {
NestedView()
}
struct NestedView: View {
var body: some View {
Text("Hello")
}
}
}
}
struct ContentView_PreviewProviders: PreviewProvider {
static var previews: some View {
NotWorking()
}
}
^^^^^^^^^^^^^^^^^^^^^^^^^^^
investigating the SampleView.1.preview-thunk.swift from ~/Library/Developer/Xcode/DerivedData/.../ directory, I found that compiler translate the above code into pre-compiled stage using typealias without considering the Generic condition-
^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
extension NotWorking.InitialView.NestedView {
typealias InitialView = NotWorking.InitialView
typealias NestedView = NotWorking.InitialView.NestedView
@_dynamicReplacement(for: body) private var __preview__body: some View {
#sourceLocation(file: "/Users/giuseppe/Development/Private/Dev/MyPlayground/MyPlayground/SampleView.swift", line: 40)
Text(__designTimeString("#32812.[2].[1].[1].[0].property.[0].[0].arg[0].value", fallback: "Hello"))
#sourceLocation()
}
}
extension NotWorking.InitialView {
typealias InitialView = NotWorking.InitialView
typealias NestedView = NotWorking.InitialView.NestedView
@_dynamicReplacement(for: body) private var __preview__body: some View {
#sourceLocation(file: "/Users/giuseppe/Development/Private/Dev/MyPlayground/MyPlayground/SampleView.swift", line: 35)
NestedView()
#sourceLocation()
}
}
extension NotWorking {
@_dynamicReplacement(for: body) private var __preview__body: some View {
#sourceLocation(file: "/Users/giuseppe/Development/Private/Dev/MyPlayground/MyPlayground/SampleView.swift", line: 30)
InitialView<String>()
#sourceLocation()
}
}
...
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Should be considered a compiler bug or I missed something in my code?
Hi all,
when I am trying to build a preview I am always getting the error "Failed to launch app in reasonable time". When clicking on Diagnostics I get the following report information:
AppLaunchTimeoutError: Failed to launch app ”SwiftUI-Weather.app” in reasonable time
The app ”SwiftUI-Weather.app” did not launch on ”iPhone 15 Pro” in 15 seconds.
bundle identifier: tregnet.SwiftUI-Weather
device name: iPhone 15 Pro
path: /Users/MyUser/Library/Developer/Xcode/DerivedData/SwiftUI-Weather-fvxpuqojpxxuqtbuzmjvlatlmuqy/Build/Intermediates.noindex/Previews/SwiftUI-Weather/Products/Debug-iphonesimulator/SwiftUI-Weather.app
Also clicking on "Generate Report" in the Diagnostics menu is not doing anything for me, even after waiting for a few minutes.
Any help would be appreciated.
Greetings