imageWithSize in Swift3

和自甴很熟 提交于 2019-12-12 01:52:42

问题


I am converting a project from Xcode 7 iOS 9 Swift 2 to Xcode 8 iOS 10 Swift 3. I let Xcode convert to the latest and it produced:

 let artWork = delegate.musicPlayer.nowPlayingItem?.value(forProperty: MPMediaItemPropertyArtwork)
 let imageForButton = (artWork as AnyObject).image(at: CGSize(width: 300, height: 300))

This resulting code crashes the app and pops the error:

-[_SwiftValue imageWithSize:]: unrecognized selector sent to instance 0x17008cdf0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue imageWithSize:]: unrecognized selector sent to instance

For completeness, the original line in Xcode 7 Swift 2 was:

let imageForButton = artWork?.imageWithSize(CGSizeMake(300, 300))

What is the correct way to size an image in Swift 3?


回答1:


valueForProperty returns Any?, you need to cast the value to the actual type

if let artWork = delegate.musicPlayer.nowPlayingItem?.value(forProperty: MPMediaItemPropertyArtwork) as? MPMediaItemArtwork {
    let imageForButton = artWork.image(at: CGSize(width: 300, height: 300))
}


来源:https://stackoverflow.com/questions/39689805/imagewithsize-in-swift3

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