【问题标题】:Displaying image in Swift在 Swift 中显示图像
【发布时间】:2018-09-04 14:36:02
【问题描述】:

关于如何在 object-c 中使用 imageWithContentsOfFile 的例子很多,但是我如何在 Swift 中使用它。 imageView.image = UIImage(imageWithContentsOfFile: imageName) 返回参数标签 '(imageWithContentsOfFile:)' 不匹配任何可用的重载

如果我写:imageView.image = UIImage(contentsOfFile:imageName) 它不显示图像。

(我在 Media.xcassets 中有所有图像存储) 我正在显示很多图像,因此使用 UIImage(named:imageName) 不是一个可行的选择。如何快速获取 contentsOfFile 的功能?

【问题讨论】:

  • 你用的是哪个 swift 版本?
  • UIImage(contentsOfFile:) 在 Swift 4 中是正确的。但它需要文件 URL,而不是文件名......无论如何:请阅读 Apple 的文档。
  • 看到这个对你有帮助stackoverflow.com/questions/37574689/…

标签: ios swift image uiimage


【解决方案1】:

Swift 代码:

func getImage (named name : String) -> UIImage?
{
    if let imgPath = Bundle.main.path(forResource: name, ofType: ".png")
    {
        return UIImage(contentsOfFile: imgPath)
    }
    return nil
}

//Image name "MyImage.png"

getImage(named: "MyImage")!

【讨论】:

  • 请解释代码应该做什么以及它应该如何提供帮助。他们专门询问您根本没有提及的imageWithContentsOfFile。最好的问候
猜你喜欢
  • 2014-11-29
  • 2021-10-15
  • 2016-06-15
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多