ios - 在 View 上强制使用特定的 Size Class

标签 ios objective-c autolayout nslayoutconstraint size-classes

我认为 iPad 和 iPhone 版本之间需要不同的约束。

登录屏幕在 iPhone 上显示为全屏,在 iPad 上显示为页面表单。由于大小的原因,UITextFields 在 iPhone 上距左右两侧 40 像素,但我希望它们在 iPad 上为 80 像素。我将其设置为最终值大小类(w Regular,h Regular)的特定约束。

但是,因为此 View 显示在页面上,所以它不使用最终值大小类。理想情况下,我想“强制” View 使用大小类,而不是使用一组 iPhone/iPad 约束和大量约束 Outlet。

最佳答案

实现此目的的方法是在 UIViewController 上使用特征集合,通过调用 -setOverrideTraitCollection:forChildViewController: 即可轻松实现。

但是,正如 API 标题所示,UIViewController 的 traitCollection 只能被其父级覆盖。 Presented View Controllers 不是其父项的子项(头文件特别说明了 Presented View Controllers 不包含在 Child View Controllers 中),因此您必须添加“ToPresentViewController”。

在这个例子中,在 IB 中有一个 ToPresentViewController 场景,它只是一个容器 ViewController 附加到它的边上,约束为 0,并且将嵌入呈现的 View Controller 。

@implementation ToPresentViewController


-(void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];

    if(thisDevice.userInterfaceIdiom != UIUserInterfaceIdiomPad)
    {
        return;
    }

    for (UIViewController *controller in self.childViewControllers) { //Should be only one
        UITraitCollection *regularWidthTraits = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular];
        [self setOverrideTraitCollection:regularWidthTraits forChildViewController:controller];
    }

}

这会将尺寸等级锁定为 iPad 上的常规尺寸。

编辑:WWDC sample code here suggests 表示只需要提供被覆盖的特征,这是有道理的,因为在原始答案中,旧+新合并集合并不清楚它是如何知道使用哪个的。

关于ios - 在 View 上强制使用特定的 Size Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28676042/

相关文章:

ios - iOS中的NSNumber等效错误

javascript - Keydown 允许数字但不能在 iPhone 上换档符号

ios - APNS : is APNS certificate needed if Auth Key using?

ios - UITabBarController 等待加载 UIViewController 直到选择 Xamarin

objective-c - 使 UIScrollview 滚动

iphone - ios 自动布局 : Programmatically set width constraint

ios - 如何在 iOS 中从服务器接收二进制文件列表

ios - 以编程方式按下 UIButton 时更改 UIImageView 中的图像

ios - 自动布局按比例缩放 View

ios - UITableViewCell 下边距约束