无法转换UILayoutPriority类型的值

时间:2017-08-10 15:49:20

标签: ios11 swift4

我试图将约束的优先级更改为高于另一个约束的优先级。在Swift 4 / iOS 11中,此代码不再编译:

let p = self.lab2.contentCompressionResistancePriority(for:.horizontal)
self.lab1.setContentCompressionResistancePriority(p+1, for: .horizontal)

我该怎么做?

2 个答案:

答案 0 :(得分:13)

在Swift 4 / iOS 11中,UILayoutPriority不再是一个简单的数字;它是RawRepresentable结构。你必须通过传递结构的rawValue来进行算术运算。

如果有以下扩展名可能很有用:

extension UILayoutPriority {
    static func +(lhs: UILayoutPriority, rhs: Float) -> UILayoutPriority {
        let raw = lhs.rawValue + rhs
        return UILayoutPriority(rawValue:raw)
    }
}

现在,+运算符可用于将UILayoutPriority与数字组合在一起,就像过去一样。现在,您的问题中的代码将正确编译(并正常工作)。

答案 1 :(得分:1)

您可以像以前一样继续使用它们:

import UIKit

// MARK: - Allow to pass a float value to the functions depending on UILayoutPriority
extension UILayoutPriority: ExpressibleByFloatLiteral {
    public typealias FloatLiteralType = Float

    public init(floatLiteral value: Float) {
        self.init(value)
    }
}

// MARK: - Allow to pass an integer value to the functions depending on UILayoutPriority
extension UILayoutPriority: ExpressibleByIntegerLiteral {
    public typealias IntegerLiteralType = Int

    public init(integerLiteral value: Int) {
        self.init(Float(value))
    }
}

有关完整实施的信息,请参阅https://gist.github.com/jeremiegirault/7f73692a162b6ecf8ef60c7809e8679e