Xcode Previews

RSS for tag

Create 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

Xcode preview selectable mode real click/tap
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?
2
0
366
Oct ’23
Xcode 15 overheating Mac
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.
5
2
882
Nov ’23
#Preview unable to see other generated Swift Macro code
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.
2
2
341
Oct ’23
Mac Catalyst Modally Presented View Controllers Not Working in Xcode Live Previews
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).
1
0
486
Sep ’23
Mac Catalyst with Live Previews: Any Way to Change the Size the View Controller Preview is Rendered at?
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.
0
0
341
Sep ’23
Live Preview Not Working for UIKit Unless I raise Deployment Target to iOS 17
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.
3
2
2.1k
Oct ’23
UIKit Live Preview for Objective-C View Controller?
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)?
4
0
901
Sep ’23
Trouble with new XCode 15 Preview Macro for Widgets
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
2
0
1.5k
Sep ’23
Xcode 15.0 (15A240d) - Preview Provider Orientation
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) }
1
0
632
Sep ’23
Xcode 15 (15A240d): Cannot preview in this file
I downloaded Xcode 15, and tried to create a new macOS project. But after it opens up, I cannot see the preview, neither am I able to run the application. I get the following error in the debugger console when I try to run the application: dyld[4339]: Symbol not found: _$s21DeveloperToolsSupport7PreviewV7SwiftUIE_6traits4bodyACSSSg_AA0D5TraitVyAC10ViewTraitsOGdAD0J0_pyScMYcctcfC Referenced from: &lt;B71F07A5-FC93-303C-8B33-1607EA5185FC&gt; /Users/monawwar/Library/Developer/Xcode/DerivedData/TestApp-dndfpagiijwwzvfkoioloexccazm/Build/Products/Debug/TestApp.app/Contents/MacOS/TestApp Expected in: &lt;5CBA1C3F-43C5-3529-8130-C71BAB1413D5&gt; /System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI
1
1
513
Sep ’23
xCode Version 15.0 - Simulator Screen Shots for 5.5 inch iPhone
In order to submit your app for review you must provide a screenshot for the 5.5 inch iPhone (iPhone 6S Plus, 7 Plus, 8 Plus). The simulator for these phones is not included in the standard set provided in xCode. After researching there is a method described where you can download simulator sets for previous iOS releases. I downloaded both the iOS 13 and iOS 14 set but still unable to get at one of the mentioned iPhone simulators. Has anyone solved this problem short of getting an actual iPhone hardware to do the screen shots on. Thanks,
13
3
5.7k
Oct ’23
User location undefined in SwiftUI Preview
In the wwdc2023-10043 session, the instructor adds a MapUserLocationButton towards the end, which seems to work fine in the SwiftUI Preview for him. However, when I follow this tutorial and add the very same button, I get a never-ending spinning wheel upon clicking it in SwiftUI Preview. I guess that the SwiftUI Preview cannot get a user location. I searched in various places whether I could set the user location, as possible in the simulator, but to no avail. In the Debug menu, there is a Simulate Location submenu, but it totally deactivated (greyed out). Does anyone know how to allow SwiftUI Preview to get an actual user location, i.e., either the one from my Mac or one that I could provide to the SwiftUI Preview simulator?
2
0
1k
Sep ’23
Failed to preview iOS app due to RealityKitContent.rkassets (should be linked only on visionOS)
Hello! My app supports iOS and visionOS in a single target. But when I preview the app on iOS device/simulator, an error occurred: The RealityKitContent.rkassets is located in my RealityKitContent package that is linked on visionOS. It seems that Xcode Preview is ignoring the link settings and attempt to build RealityKitContent.rkassets on iOS. Reproduce Steps: Clone my demo project at https://github.com/gongzhang/rkassets-preview-issue-demo Build the app for iOS (success) Preview ContentView.swift (failed due to RealityKitContent.rkassets issue)
3
0
789
Sep ’23
Xcode Previews bug? View is not re-rendered as expected
I've made a small reproducing example app to demonstrate this issue. Just create an iOS App project and replace the App and ContentView files with the following code. The app works as expected when running it in a simulator or on a device but the SwiftUI Preview will get stuck showing only the loading state, even though the print statement in the View's body has printed viewModel.state: showingContent(SwiftUITest.ViewModel.Content(text: "Hello world!", reloadButtonTitle: "Reload"))to the console. When stuck showing the loading state (an animated ProgressView), If I change .padding(.all, 12) to e.g. .padding(.all, 2) or vice versa, then that will make the Preview render the expected content. Also, if I tap the Reload-button, it will not show the ProgressView for 2 seconds as expected (and as the app will do when run in a simulator or on a device), instead it will just show a white screen, and the same workaround (changing the padding amount) can be used to make the it render the expected content. Can other people reproduce this behavior, is it a known bug, or am I doing something wrong? TestApp.swift import SwiftUI @main struct SwiftUITestApp: App { var body: some Scene { WindowGroup { ContentView(viewModel: ViewModel( contentLoader: { try! await Task.sleep(nanoseconds: 2_000_000_000) return .init(text: "Hello world!", reloadButtonTitle: "Reload") } )) } } } ContentView.swift import SwiftUI struct ContentView: View { @StateObject var viewModel: ViewModel var body: some View { let _ = print("viewModel.state:", viewModel.state) Group { switch viewModel.state { case .notStarted, .loading: ProgressView() case .showingContent(let content): VStack { Text(content.text) .padding(.all, 12) Button(content.reloadButtonTitle) { viewModel.handle(event: .reloadButtonWasTapped) } } } } .onAppear { viewModel.handle(event: .viewDidAppear) } } } // MARK: - ViewModel @MainActor final class ViewModel: ObservableObject { @Published var state: State = .notStarted let contentLoader: () async -> Content init(contentLoader: @escaping () async -> Content) { self.contentLoader = contentLoader } func handle(event: Event) { switch state { case .notStarted: if event == .viewDidAppear { loadContent() } case .loading: break case .showingContent: if event == .reloadButtonWasTapped { loadContent() } } } func loadContent() { guard state != .loading else { return } state = .loading Task { print("starts loading", Date.now) let content = await contentLoader() print("finished loading", Date.now) state = .showingContent(content) } } enum State: Equatable { case notStarted case loading case showingContent(Content) } struct Content: Equatable { let text: String let reloadButtonTitle: String } enum Event: Equatable { case viewDidAppear case reloadButtonWasTapped } } // MARK: - Preview struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(viewModel: ViewModel( contentLoader: { try! await Task.sleep(nanoseconds: 2_000_000_000) return .init(text: "Hello world!", reloadButtonTitle: "Reload") } )) } } Here's the simple behavior of the app (recorded from simulator): Each time the view appears, it loads it's content for two seconds while showing a ProgressView, then it shows the content, which includes a Reload button, and if you tap that button it will reload the content for 2 seconds again. I would expect the Preview to behave in the same way.
2
0
933
Sep ’23