在 Swift 中利用 UIUserInterfaceIdiom 檢測當前裝置


為了用 iOS/Swift 檢測當前裝置,我們可以使用 UserInterfaceIdiom。它是一個 Swift 列舉,指示正在使用的裝置。

介面習慣用語在它的列舉中提供多個值,它們是。

case unspecified
@available(iOS 3.2, *)
case phone // iPhone and iPod touch style UI
@available(iOS 3.2, *)
case pad // iPad style UI
@available(iOS 9.0, *)
case tv // Apple TV style UI
@available(iOS 9.0, *)
case carPlay // CarPlay style UI

在 swift 中,可以這樣使用 interfaceIdiom

print(UIDevice.current.userInterfaceIdiom)
if UIDevice.current.userInterfaceIdiom == .phone {
   print("running on iPhone")
}

當我們在 iPhone 裝置上執行以上程式碼時,會產生以下結果。

更新於:30-7 月 -2019

2K+ 瀏覽量

開啟職業生涯

完成課程獲取認證

開始行動
廣告
© . All rights reserved.