Xcode SwiftUI Preview for ViewController's view (UIView subclass)

 

主要是參考這篇:

https://www.avanderlee.com/xcode/xcode-previews/

可以在Debug的時候,使用Swift UI Preview功能,

但又能在Release的時候,build成PM要求的iOS最低版本
 

 

1.SwiftUIPreview.swift

#if canImport(SwiftUI) && DEBUG
import SwiftUI

@available(iOS 13.0, *)
struct ViewControllerRepresentable: UIViewRepresentable where T: UIViewController {

    func makeUIView(context: Context) -> UIView {
        return T().view
    }
    
    func updateUIView(_ view: UIView, context: Context) {
        
    }
}

#endif

2.RecommendScheduleCollectionViewCellPreview.swift

#if canImport(SwiftUI) && DEBUG
import SwiftUI

@available(iOS 13.0, *)
struct RecommendScheduleCollectionViewCellPreview: PreviewProvider {
    
    struct Representable: UIViewRepresentable {

        let cell = RecommendScheduleCollectionViewCell()
        
        init(item: RecommendSchedule) {
            cell.schedule = item
        }
        
        func makeUIView(context: Context) -> UIView {
            return cell
        }
        
        func updateUIView(_ view: UIView, context: Context) {
            
        }
    }
    
    static var previews: some View {

        return Group {
            Representable(item: RecommendSchedule(
                titleText: "台灣WiFi機租借|4G上網吃到飽|台灣機場領取 TPE/TSA/KHH",
                imageURL: "https://xxx/image",
                rating: 1,
                ratingCount: 50,
                price: "499",
                currency: "TWD"
            )).previewLayout(.fixed(width: 375, height: 87))
            
            Representable(item: RecommendSchedule(
                titleText: "台灣WiFi機租借|4G上網吃到飽|台灣機場領取 TPE/TSA/KHH",
                imageURL: "https://xxx.com/image",
                rating: 0,
                ratingCount: 50,
                price: "499",
                currency: "TWD"
            )).previewLayout(.fixed(width: 375, height: 87))
            
            Representable(item: RecommendSchedule(
                titleText: "台灣WiFi機",
                imageURL: "https://xxx/image",
                rating: 3.5,
                ratingCount: 50,
                price: "4999999999999",
                currency: "TWD"
            )).previewLayout(.fixed(width: 375, height: 87))
        }
    }
}

#endif

 

(塞假資料的地方)

 

(Preview畫面)

 

(整個ViewController也行)

 

(可以塞些fake json)

 

Preview build的時間比Command + B的增量編譯快,約8~40秒之間

 

 

結論:

使用Swift UI Preview可以大幅提高修改跟測試UI方面的生產力

文章標籤
全站熱搜
創作者介紹
創作者 小賢 的頭像
小賢

小賢的部落格

小賢 發表在 痞客邦 留言(0) 人氣(17)