【发布时间】:2015-11-24 17:50:36
【问题描述】:
在运行 Xcode UI 测试时,我想知道正在使用哪个设备/环境(例如 iPad Air 2、iOS 9.0、模拟器)。
我怎样才能得到这些信息?
【问题讨论】:
标签: ios testing xcode7 xcode-ui-testing
在运行 Xcode UI 测试时,我想知道正在使用哪个设备/环境(例如 iPad Air 2、iOS 9.0、模拟器)。
我怎样才能得到这些信息?
【问题讨论】:
标签: ios testing xcode7 xcode-ui-testing
使用 Swift 3(根据需要将 .pad 更改为 .phone):
if UIDevice.current.userInterfaceIdiom == .pad {
// Ipad specific checks
}
使用旧版本的 Swift:
UIDevice.currentDevice().userInterfaceIdiom
【讨论】:
不幸的是,没有直接查询当前设备的方法。但是,您可以通过查询设备的尺寸等级来解决问题:
private func isIpad(app: XCUIApplication) -> Bool {
return app.windows.elementBoundByIndex(0).horizontalSizeClass == .Regular && app.windows.elementBoundByIndex(0).verticalSizeClass == .Regular
}
正如您在Apple Description of size classes 中看到的,只有 iPad 设备(当前)同时具有垂直和水平尺寸类别“Regular”。
【讨论】:
您可以使用windows 元素框架XCUIApplication().windows.element(boundBy: 0).frame 进行检查并检查设备类型。
您还可以使用currentDevice 属性为XCUIDevice 设置扩展名:
/// Device types
public enum Devices: CGFloat {
/// iPhone
case iPhone4 = 480
case iPhone5 = 568
case iPhone7 = 667
case iPhone7Plus = 736
/// iPad - Portraite
case iPad = 1024
case iPadPro = 1366
/// iPad - Landscape
case iPad_Landscape = 768
case iPadPro_Landscape = 0
}
/// Check current device
extension XCUIDevice {
public static var currentDevice:Devices {
get {
let orientation = XCUIDevice.shared().orientation
let frame = XCUIApplication().windows.element(boundBy: 0).frame
switch orientation {
case .landscapeLeft, .landscapeRight:
return frame.width == 1024 ? .iPadPro_Landscape : Devices(rawValue: frame.width)!
default:
return Devices(rawValue: frame.height)!
}
}
}
}
用法
let currentDevice = XCUIDevice.currentDevice
【讨论】:
也许有人会为 XCTest on Objective C 派上用场:
// Check if the device is iPhone
if ( ([[app windows] elementBoundByIndex:0].horizontalSizeClass != XCUIUserInterfaceSizeClassRegular) || ([[app windows] elementBoundByIndex:0].verticalSizeClass != XCUIUserInterfaceSizeClassRegular) ) {
// do something for iPhone
}
else {
// do something for iPad
}
【讨论】:
var isiPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
【讨论】:
使用 iOS13+,您现在可以使用 UITraitCollection.current 获取当前环境的完整特征集。 (doc)
如果您只想获取特征集合的水平/垂直大小类,您可以通过在测试中访问 myXCUIElement.horizontalSizeClass 和 .verticalSizeClass 来更好地向后兼容您的测试(Xcode 10.0+),因为它们通过所有 UI 元素采用的XCUIElementAttributes 协议公开。 (请注意,虽然我在取消XCUIApplication() 时收到了.unspecified;最好在窗口中使用真实的UI 元素。如果您手头没有,您仍然可以始终使用app!.windows.element(boundBy: 0).horizontalSizeClass == .regular 之类的东西作为过去提到过。)
【讨论】: