问题
I'm getting an image's Size
and used the below code. It was working perfectly fine with Xcode 6.0.1
. After updating to Xcode 6.1
, I'm getting Error Like :
'UIImage?' does not have a member named 'size'
var image = UIImage(named: imageName)
let sizeOfImage = image.size
Is it bug with my code or Apple ? Please help me in here. TIA.
回答1:
That initializer is now a failable initializer, and as such it returns an optional UIImage
.
To quickly fix your bug just unwrap the image:
let sizeOfImage = image?.size
but I presume you will reference the image
variable more than just once in your code, in that case I suggest using optional binding:
if let image = image {
let sizeOfImage = image.size
/// ...
/// Use the image
}
回答2:
In addition to @Antonio's answer you can use nil coalescing operator(??) to get a default size in case image initializer is failed. Here is how:
let size = image?.size ?? CGSizeZero
回答3:
Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. In your case: image.size!
回答4:
you can use like this:
let image = UIImage(named: "photo1.png")
let sizeOfImage = image?.size
imageView.image = image
imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: sizeOfImage!)
来源:https://stackoverflow.com/questions/26582035/in-xcode-6-1-uiimage-does-not-have-a-member-named-size-error