I'm trying to change the priority of a constraint to be higher than that of another constraint. In Swift 4 / iOS 11, this code no longer compiles:
let p = self.lab2.contentCompressionResistancePriority(for:.horizontal)
self.lab1.setContentCompressionResistancePriority(p+1, for: .horizontal)
How am I supposed to do this?
In Swift 4 / iOS 11, UILayoutPriority is no longer a simple number; it's a RawRepresentable struct. You have to do your arithmetic by passing through the rawValue
of the struct.
It may be useful to have on hand an extension such as the following:
extension UILayoutPriority {
static func +(lhs: UILayoutPriority, rhs: Float) -> UILayoutPriority {
let raw = lhs.rawValue + rhs
return UILayoutPriority(rawValue:raw)
}
}
Now the +
operator can be used to combine a UILayoutPriority with a number, as in the past. The code in your question will now compile (and work) correctly.
EDIT In iOS 13 this extension is no longer needed, as it is incorporated directly into system (plus you can now initialize a UILayoutPriority without saying rawValue:
). Still, it beats me why Apple ever thought it was a good idea to make a priority
anything other than a number, because that is all it is or needs to be.
You can do the following to continue using them as before:
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))
}
}
Refer to https://gist.github.com/jeremiegirault/7f73692a162b6ecf8ef60c7809e8679e for a full implementation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With