Preview Devices
有了下列的 extension:
import SwiftUI
extension PreviewDevice {
// ⭐️ `PreviewDevice` conforms to `ExpressibleByStringLiteral`
static let iPhone13ProMax: PreviewDevice = "iPhone 13 Pro Max"
static let iPhone13Pro : PreviewDevice = "iPhone 13 Pro"
}
就可以使用下列語法:
.previewDevice(.iPhone13Pro) // ⭐️ use static member
使用下列 extension:
extension View {
/// .previewDevice(deviceName)
public func previewDevice(_ deviceName: String) -> some View {
previewDevice(PreviewDevice(rawValue: deviceName))
}
}
則可用下列語法:
// string constant
let deviceName = "iPhone X"
.previewDevice(deviceName) // ⭐️ not a string literal
.previewDevice() 要接收一個 PreviewDevice? 參數,但可以使用:
.previewDevice("iPhone XS Max")
的語法,是因為 PreviewDevice conforms to ExpressibleByStringLiteral
如果直接使用下列語法會產生錯誤:
.previewDevice(deviceName) // var deviceName = "iPhone X"
因為 deviceName
是一個 String variable,並不是 String literal。
所以如果不做任何擴充,我們只能使用:
.previewDevice(PreviewDevice(rawValue: deviceName))
SwiftUI Tutorials ⟩ Sec. 8: Generate Previews Dynamically - Step 2
View ⟩ .previewDevice(_:)
PreviewDevice (struct)
Last updated