鉴于这种情况:
XCPlaygroundPage.currentPage.liveView = TableViewController()
是否可以模拟设备的方向?
答案 0 :(得分:2)
基于here KIF testing framework中的某些逻辑,我认为应该是可能的。
链接后面的Objective-C代码如下所示:
- (void)simulateDeviceRotationToOrientation:(UIDeviceOrientation)orientation
{
[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:orientation] forKey:@"orientation"];
}
此代码的Swift等价物如下所示:
func simulateDeviceRotation(toOrientation orientation: UIDeviceOrientation) {
let orientationValue = NSNumber(integer: orientation.rawValue)
UIDevice.currentDevice().setValue(orientationValue, forKey: "orientation")
}
然后我们称之为:
simulateDeviceRotation(toOrientation: .LandscapeLeft)
或许我们想要一个为每个方向运行一些代码的函数?
func forEachOrientation(block: () -> Void) {
for orientation in [UIDeviceOrientation.Portrait, UIDeviceOrientation.LandscapeLeft, UIDeviceOrientation.PortraitUpsideDown, UIDeviceOrientation.LandscapeRight] {
simulateDeviceRotation(toOrientation: orientation)
block()
}
}
我们可以这样称呼它:
forEachOrientation {
// do a thing
}
根据我的经验,这实际上似乎不适用于iOS 9模拟器,但它确实适用于iOS 8模拟器。我不知道这是否适用于真实设备。