我对UITraitCollection有一个简单的扩展名:

extension UITraitCollection {

    var isIpad: Bool {
        return horizontalSizeClass == .Regular && verticalSizeClass == .Regular
    }
}

以前,我需要为此编写测试(使用TDD):
let traitCollection = UITraitCollection(verticalSizeClass: .Regular) //the init is either for vertical or horizontal at time
traitCollection.horizontalSizeClass = .Regular //error

XCTAssertTrue(traitCollection.isIpad)

但是错误是:

无法分配给属性:horizontalSizeClass是仅获取属性。

那我该怎么办?

最佳答案

好的,我找到了解决方案:

let compactTraitCollection = UITraitCollection(traitsFromCollections: [UITraitCollection(verticalSizeClass: .Compact), UITraitCollection(horizontalSizeClass: .Compact)])
XCTAssertFalse(compactTraitCollection.isIpad)

let regularTraitCollection = UITraitCollection(traitsFromCollections: [UITraitCollection(verticalSizeClass: .Regular), UITraitCollection(horizontalSizeClass: .Regular)])
XCTAssertTrue(regularTraitCollection.isIpad)

09-05 20:18