“Int is not convertible to CGFloat” error when subclassing UIImageView

☆樱花仙子☆ 提交于 2020-01-07 01:19:28

问题


I have a weird bug here.

I'm subclassing UIImageView to pass some custom properties to my views. If I don't add an init method to my subclass, everything's fine.

But if I do add the init (and I'm required to do so), then when I'm creating the frame view the compiler complains that an Int is not convertible to CGFloat.

Le subclass with Le init :

class CustomUIImageView : UIImageView {


let someParameter : Bool

init(someParameter: Bool) {
    self.someParameter = someParameter
    println("\(someParameter) is being initialized")
}

//Since the release of the GM version of XCode 6, it's asking me to pass this init below 
//if I'm initializing a value. Frankly, I've no idea why, what's for nor what should I do about it. 
required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

deinit {
    println("\(someParameter) is being deinitialized")
}
}

And Le error when creating the Frame.

 var myView: CustomUIImageView!
 myView = CustomUIImageView(frame: (CGRectMake(0, 0, 100, 100)))
 //compiler says "Int is not convertible to CGFloat". 

Is this some kind of bug, or did I do something wrong (which is highly plausible)?

Edit : I've read that I need to convert directly to a CGFloat by doing like this : myView = CustomUIImageView(frame: (CGRectMake(CGFloat(0), 0, 100, 100))) But then compiler complains again saying that "Type () does not conform to protocol 'IntergerLiteralConvertible'".


回答1:


In your init you forgot to call the parent initializer:

init(someParameter: Bool) {
    self.someParameter = someParameter
    println("\(someParameter) is being initialized")

    super.init() // << this is missing
}

However it looks like there's another initializer which is required but not said explicitly:

override init(frame: CGRect) {
    self.someParameter = false
    super.init(frame: frame)
}

That should solve the compilation issue - what's left is figuring out how to initialize the properties implemented in your class - maybe you should use optionals.



来源:https://stackoverflow.com/questions/25949217/int-is-not-convertible-to-cgfloat-error-when-subclassing-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!