Mobile Development 17 min read

Using Xcode Canvas to Preview Objective‑C UI with SwiftUI Previews

This article explains how to enable Xcode Canvas previews for legacy Objective‑C views by leveraging SwiftUI's PreviewProvider, detailing the required project settings, bridging‑header configuration, code examples, and troubleshooting steps for integrating preview support into large iOS codebases.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Using Xcode Canvas to Preview Objective‑C UI with SwiftUI Previews

The author describes the motivation behind using SwiftUI previews—real‑time UI rendering—and the challenge of applying this to existing Objective‑C projects that target iOS 9‑12.

By observing that Xcode can preview any file it understands, the article explains that a file ending with .swift must contain a struct conforming to PreviewProvider ; Xcode then creates a hidden *.preview‑thunk.swift file and loads a generated *.preview‑thunk.dylib at runtime to update the preview instantly.

To make an Objective‑C view previewable, two steps are required: (1) create a PreviewProvider that returns a SwiftUI view wrapping the Objective‑C UI, and (2) expose the Objective‑C class to Swift via a dedicated Preview‑Header.h imported in the project’s bridging header.

import Foundation
import UIKit
#if canImport(SwiftUI)
import SwiftUI
@available(iOS 13.0, *)
struct UIView_Preview: PreviewProvider {
    static var previews: some View {
        Text("我是自定义 SwiftUI视图")
    }
}
#endif

The article then walks through integrating this approach into three real projects (a large CocoaPods‑based app, a newer project, and a Carthage‑based app), listing common issues such as missing Swift_Version , SWIFT_OPTIMIZATION_LEVEL , static vs. dynamic library conflicts, and runtime crashes caused by missing SwiftUI frameworks on iOS 11 devices.

Solutions include setting the Swift version to 5, using -Onone for debug builds, adjusting library search paths, making the SwiftUI framework optional, and adding preview assets to the "Development Assets" build setting.

Finally, the author notes performance considerations (Canvas refresh speed equals app launch time), the need for cleaning precompiled headers after bridging‑header changes, and the limitations of previewing Objective‑C code compared to native SwiftUI development.

mobile developmentiOScanvasXcodeSwiftUIObjective-Cpreview
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.