模态视图上的大小 类

Size classes on Modal Views

我正在尝试为 iPad 和 iPhone (4'') 设置不同的约束。

我已经为 iPhone 设置了常规高度和紧凑宽度限制。但这些限制显示在 7.9'' iPad、9.7'' iPad.

这些约束适用于模态视图。

如何将我的常规高度和紧凑宽度限制限制为我的 iPhone。

因为在 iPad 上呈现的 sheet 形式是紧凑宽度和常规高度,它采用了这些约束。

Formsheet ios 8 constraints are same as iphones constraints

解决方案是覆盖 Presented 视图控制器中的 traitCollection

override var traitCollection: UITraitCollection
{
    if UIDevice.isIPad()
    {
        let traits = UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClass.Regular)
        let traits2 = UITraitCollection(verticalSizeClass: UIUserInterfaceSizeClass.Regular)
        let traitCollection = UITraitCollection(traitsFromCollections: [traits, traits2])

        return traitCollection
    }
    else
    {
        return super.traitCollection
    }
}

请注意,iOS 文档对 traitCollection 有此警告:

Use the traitCollection property directly. Do not override it. Do not provide a custom implementation.

众所周知,这是一个 Obj-C 解决方案,它结合了 super 特征和更新的 horizontal/vertical 特征:

- (UITraitCollection *)traitCollection {
    UITraitCollection *traitCollection = [super traitCollection];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        UITraitCollection *horizontalTraitCollection = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular];
        UITraitCollection *verticalTraitCollection = [UITraitCollection traitCollectionWithVerticalSizeClass:UIUserInterfaceSizeClassRegular];
        traitCollection = [UITraitCollection traitCollectionWithTraitsFromCollections:@[traitCollection, horizontalTraitCollection, verticalTraitCollection]];
    }
    return traitCollection;
}