2017-08-10 35 views
0

我有一个PNG图像数组。如何在swift 3中使用UIImage,数组是否为零?

iconeImage = [UIImage(named:"ion-home")!,UIImage(named:"ms-medkit")!,UIImage(named:"ion-edit")!,UIImage(named:"ion-clipboard")!,UIImage(named:"ion-clipboard")!,UIImage(named:"ion-waterdrop")!,UIImage(named:"ion-calendar")!] 

,我有表视图一个功能,与此数组元素

设置图像这里是代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell 
     cell.imgIcon.image = iconeImage[indexPath.row] 
     return cell 
    } 

但它给我的错误iconeImage具有零值。所以你可以建议我解决方案。我是初学者在迅速3

下面是截图 a busy cat 【二布偶] [1]

+0

您的项目中是否真的有名为'ion-home'的图像?每一个都一样? – Larme

+0

看起来好像实际上没有匹配所有这些图像名称的图像,或者您可能没有将它们存储在正确的位置。除非它们是“Assets.xcassets”的一部分,否则您还需要在图像名称中指定扩展名。 –

+0

如果它说'iconeImage'是'nil',或者它有'0'图像,这意味着上面的代码从未被执行,或者内容被其他部分替换。另一方面,如果其中一个映像管理器应该返回零,则该应用程序会崩溃,说你有一个意想不到的零(因为强制unwrapps“!”)。 – Daniel

回答

1

我不知道到底是什么问题。

但是,当我搜索了stackoverflow。地方我读的东西问题Assets.xcassets

然后我得到了确切的this

错误,然后与答案的帮助下解决了错误。

并希望我解决了错误。

与此同时问题是与资产文件夹。

2

请尝试以下格式

let img = iconeImage[indexPath.row] 
    if let imgData = img { 
     cell.imgView.image = UIImage(data:imgData) 
    } 
2

您可以将您的图片名称改为:

let iconImageNames = ["ion-home","ms-medkit", ... , "ion-calendar")] 

后来在您的方法中访问它们:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell 
    let name = iconeImage[indexPath.row] ?? yourDefaultImageName 
    cell.imgIcon.image = UIImage(named: name) 
    return cell 
} 

举个例子

+0

我已经试过这个,但得到相同的错误 –

+0

@sanjayrathod,告诉我你的iconImage是如何定义的 –

+0

iconeImage = [“ion-home”,“ms-medkit”,“ion-edit”,“ion-clipboard”,“ion -clipboard“,”ion-waterdrop“,”ion-calendar“] –

3

而不是拿在记忆我建议你存储的图片名称的所有图像:

let iconImages = ["ion-home", "ms-medkit", "ion-edit", "ion-clipboard", "ion-waterdrop", "ion-calendar"] 

,并直接预装每一个图像,当你需要它。它不会影响性能,因为它是小图标。另外代码看起来更干净。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell 
    cell.imgIcon.image = UIImage(named: iconImages[indexPath.row]) 
    return cell 
} 

仔细检查是否所有的资产都添加到您的项目。如果他们在那里,应该显示图像。

尽量避免在代码中使用隐式解包可选(!)。无值将会使应用程序崩溃。在你的例子中,imageView.image是一个可选的,所以你可以设置UIImage(名为:“imageName”)。

另外,您可以尝试清理生成文件夹,清理项目并重新安装应用程序。有时在Xcode中复制资源失败。

+0

我已经试过,但得到了同样的错误 - 如果Assets.xcassets添加到您的目标 –

+0

检查。打开资产文件,在右侧菜单中点击1选项卡。检查目标会员部分,应该有你的目标名称附近的复选标记 –

相关问题