Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type UILayoutPriority

Tags:

swift4

ios11

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?

like image 844
matt Avatar asked Dec 02 '22 12:12

matt


2 Answers

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.

like image 187
matt Avatar answered Dec 07 '22 23:12

matt


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

like image 44
acecilia Avatar answered Dec 07 '22 23:12

acecilia