如何在自动布局中使两个视图之间的距离可变

How to make distance between two views variable in autolayout

我有一个从顶部布局向下 50 像素的视图。

我希望距离根据设备大小而变化,例如它应该在 4 秒内变为 30 像素,而在 iphone 秒内变为 50 像素,而在 iPhone 6 秒内变为 60 像素。

我尝试使用 宽高比 而不是垂直间距,但它不起作用。

如果我只是在所有设备上将垂直间距设置为 50px.. 请帮助我

AutoLayout 确实允许您根据屏幕设置不同的约束,但仅限于方向更改,iPad 与 iPhone 相比。您必须以编程方式进行。

This link 将向您展示如何获取设备,然后一旦您拥有该设备,您需要为您的约束创建一个@IBOutlet,然后您可以更改它的 .constant 属性 到 40、50 或 60

public extension UIDevice {

    var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        switch identifier {
        case "iPhone4,1":                               return "iPhone 4s"
        case "iPhone8,1":                               return "iPhone 6s"
        case "iPhone8,4":                               return "iPhone SE"
        default:                                        return identifier
        }
    }

}

现在你可以像这样使用它了:

@IBOutlet weak var myConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()
    if UIDevice.current.modelName == "iPhone 4s" {
        myConstraint.constant = 30
    }
    else if UIDevice.current.modelName == "iPhone SE" {
        myConstraint.constant = 50
    }
    else if UIDevice.current.modelName == "iPhone 6s" {
        myConstraint.constant = 60
    }
}

@Aziz Javed 根据您的实际需求提出了正确的解决方案。如果您想要每个设备的特定常量值,唯一的方法是按照 Aziz 建议的代码来完成。

The storyboard constrant does not have an aspect ratio property for (Top,Bottom,Left,Right,Leading,Trailing) constraints.

故事板 中的解决方案是在您的视图之上添加一个视图。在视图的顶部和底部添加一个等于零的间距约束。在添加的将起到间距作用的视图上添加一个高度约束,并将纵横比设置为屏幕视图。