IOS9 iphone 和 ipad 的编程约束

IOS9 programmatically constraints for iphone and ipad

在视图控制器中,我以编程方式创建了 uitextfield。对于此 textField,我希望有以下限制:距离顶部 90 像素,高度 50 像素,iphone 设备的右侧和左侧 8 像素(因此宽度已调整)和 400 像素固定宽度以防万一ipad 台设备。

这是我的代码中指定了这些约束的部分:

text.topAnchor.constraint(equalTo: view.topAnchor, constant: 90).isActive = true
text.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true
text.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8).isActive = true
text.heightAnchor.constraint(equalToConstant: 50).isActive = true

此代码为 iphone 设备提供了正确的结果,但是对于 ipad 设备它不是我想要的(调整了文本字段的宽度)。我了解 ipad.

的代码块不正确

我的问题是如何以编程方式为 iphone 和 ipad 设备设置上述逻辑的约束?

我认为可能的解决方案可能是在设置约束之前检查屏幕尺寸宽度,但我不知道它是否适合此任务。

8 pixels from right and left sides for iphone devices (so the width is adjusted) and 400 pixel fixed width in case of ipad devices

首先,让我们注意,对于 iPad,您的约束指定不充分,因为您没有说明视图的 x-origin 应该在 iPad 上的什么位置。因此,出于讨论的目的,我将不得不编造一些内容:我会说您希望视图水平居中。

所以,既然已经规定了,你所要做的就是查看 traitCollection 并检查它的 userInterfaceIdiom。这会告诉您我们是在 iPad 还是 iPhone(.pad.phone),一个简单的 if/else 构造将允许您提供适当的约束集。

因此,无需我实际为您编写约束,这是您将使用的结构:

text.topAnchor.constraint(equalTo: view.topAnchor, constant: 90).isActive = true
text.heightAnchor.constraint(equalToConstant: 50).isActive = true
let dev = self.traitCollection.userInterfaceIdiom
if dev == .phone {
    text.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true
    text.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8).isActive = true
} else {
    text.widthAnchor.constraint...
    text.centerXAnchor.constraint...
}

为了完成@matt 的精彩回答,这里有一个示例,说明如何检查设备是 iPad 还是 iPhone。

enum UIUserInterfaceIdiom : Int {
    case unspecified

    case phone // iPhone
    case pad // iPad
}

然后您可以像这样使用它:

UIDevice.current.userInterfaceIdiom == .pad
UIDevice.current.userInterfaceIdiom == .phone
UIDevice.current.userInterfaceIdiom == .unspecified

或者,如果您更喜欢使用 Switch:

switch UIDevice.current.userInterfaceIdiom {
case .phone:
    // It's an iPhone
case .pad:
    // It's an iPad
case .unspecified:
    // Error handling
}

对于您的情况,您可以简单地使用 if/else 语句。

您只需检查 IF 设备是 iPad 还是 iPhone,然后相应地设置约束。

使用 leftAnchor 和 rightAnchor 而不是 leading/trailing 可能更适合跨设备,尽管 Apple 建议尽可能使用前导尾随。