我想测试我的应用处理方向变化(纵向/横向)的能力。我目前正在使用KIF,据我所知,它无法做到这一点。有没有办法以编程方式为 iOS 模拟器模拟旋转事件?
我不在乎它是否是一些未记录的私有 API 或 hack,因为它只会在测试期间运行,不会成为生产构建的一部分。
我想测试我的应用处理方向变化(纵向/横向)的能力。我目前正在使用KIF,据我所知,它无法做到这一点。有没有办法以编程方式为 iOS 模拟器模拟旋转事件?
我不在乎它是否是一些未记录的私有 API 或 hack,因为它只会在测试期间运行,不会成为生产构建的一部分。
这是实现此目的的步骤:
+ (KIFTestStep*) stepToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation {
NSString* orientation = UIInterfaceOrientationIsLandscape(toInterfaceOrientation) ? @"Landscape" : @"Portrait";
return [KIFTestStep stepWithDescription: [NSString stringWithFormat: @"Rotate to orientation %@", orientation]
executionBlock: ^KIFTestStepResult(KIFTestStep *step, NSError *__autoreleasing *error) {
if( [UIApplication sharedApplication].statusBarOrientation != toInterfaceOrientation ) {
UIDevice* device = [UIDevice currentDevice];
SEL message = NSSelectorFromString(@"setOrientation:");
if( [device respondsToSelector: message] ) {
NSMethodSignature* signature = [UIDevice instanceMethodSignatureForSelector: message];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: signature];
[invocation setTarget: device];
[invocation setSelector: message];
[invocation setArgument: &toInterfaceOrientation atIndex: 2];
[invocation invoke];
}
}
return KIFTestStepResultSuccess;
}];
}
注意:请将您的设备平放在桌子上,否则加速度计更新会将视图旋转回来。
要在 UI 自动化中模拟方向更改,您可以使用 UIATarget 的 setDeviceOrientation 方法。例子:
UIATarget.localTarget().setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPELEFT);
方法需要一个参数'deviceOrientation'常量。更多信息在这里
这 100% 可以在真正的 iOS 设备上运行。我不确定模拟器。
我不知道“以编程方式”是什么意思,但如果您使用苹果提供的 UIAutomation 库以及 Instruments 应用程序的自动化模板,您可以模拟 iPhone 支持的不同方向。
为什么以编程方式进行?模拟器完全符合您的要求,它测试应用程序处理方向变化的能力。
在模拟器中,使用顶部菜单 Hardware > Rotate Left / Right 或按住 Command 并使用左右箭头。