Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

ios - Swift UIColor initializer - compiler error only when targeting iPhone5s

The Situation:

Working from a new project: iOS > Application > Game > SpriteKit, Swift, iPhone

Here I've written a function in my GameScene.swift to accept a hex color value and alpha double. I am going by the Swift documentation, and referencing an elegant solution I saw online. I've noticed this exact code compiles, runs and displays the proper color for a build target of iPhone5 in the simulator.

But...

The exact same project wont even compile when my build target is set for iPhone5s.

the compiler error

Could not find an overload for 'init' that accepts the supplied arguments.

The function:

// colorize function takes HEX and Alpha converts then returns aUIColor object
func colorize (hex: Int, alpha: Double = 1.0) -> UIColor {
    let red = Double((hex & 0xFF0000) >> 16) / 255.0
    let green = Double((hex & 0xFF00) >> 8) / 255.0
    let blue = Double((hex & 0xFF)) / 255.0
    var color: UIColor = UIColor( red: Float(red), green: Float(green), blue: Float(blue), alpha:Float(alpha) )
    return color
}

The related call in didMoveToView:

override func didMoveToView(view: SKView) {

    // blue background color
    self.backgroundColor = colorize( 0x003342, alpha:1.0)

}

Admittedly I am very new to iOS development, but I am wondering what is going on to cause the compiler not to find this initializer?

EDIT: putting up a github momentarily

A quick gist with related files... the only one I've edited is GameScene.swift

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It probably has to do with a mismatch between Float and Double. Basically, if the arguments are expected to be CGFloats, you need to pass CGFloats.

let color = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))

What's important to understand here is that CGFloat is defined as Float on 32 bit platforms, and Double on 64 bit platforms. So, if you're explicitly using Floats, Swift won't have a problem with this on 32 Bit platforms, but will produce an error on 64 bit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...