Xcode 15 - Preview macro error with UIKit UIView
Asked Answered
E

1

6

In my legacy code base with public Xcode 15.0, I can't preview any UIKit views with the new #Preview macro

import SwiftUI

#Preview {
    let uiView = UIView()

    return uiView
}

The canvas fails to load preview with failure diagnostic Compiling failed: return expression of type 'UIView' does not conform to 'View'

Euterpe answered 26/9, 2023 at 17:49 Comment(0)
O
16

I find that restricting this one-statement preview to iOS 17 works:

@available(iOS 17, *)
#Preview {
    return UIView()
}

However, this two-statement preview still does not work:

@available(iOS 17, *)
#Preview {
    let uiView = UIView()
    return uiView // 🛑 Value of optional type 'UIView?' must be unwrapped to a value of type 'UIView'
}

To get the two-statement preview to work, I have to make the variable type explicit:

@available(iOS 17, *)
#Preview {
    let uiView: UIView = UIView()
    return uiView
}
Oceanic answered 27/9, 2023 at 15:41 Comment(1)
Thank you! The #Preview macro started working after I marked it @available(iOS 17, *)Pareu

© 2022 - 2024 — McMap. All rights reserved.