2017-02-09 38 views
1

在视图控制器我已经创建uitextfield编程。对于这个textField,我想要有以下约束条件:对于iphone设备,顶部90像素,高度50像素,左右各8像素(宽度调整),对于iPad设备,则为400像素固定宽度。iOS9编程约束iPhone和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设备的编程约束?

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

回答

1

8从右像素和左侧的iPhone设备(这样的宽度被调整的)和400像素的宽度固定在ipad设备的情况下

首先,让我们注意到对于iPad上的限制是不充分指定,因为你不是说视图的X原点应该在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... 
} 
3

为了完成@马特的伟大答案,这里是你如何,如果检查的例子设备是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 UIDevice.current.userInterfaceIdiom { 
case .phone: 
    // It's an iPhone 
case .pad: 
    // It's an iPad 
case .unspecified: 
    // Error handling 
} 

对于你的情况,你可以简单地使用的if/else声明。

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

0

尽管Apple建议尽可能使用前导尾随,但使用leftAnchor和RightAnchor替代前导/尾随可能更适合跨设备。