簡體   English   中英

swift 3中如何使用UIImage數組為零?

[英]How to use UIImage in swift 3 the array comes nil?

我有一組png圖像。

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具有nil值。 所以你能給我建議解決方案。 我是Swift 3的初學者

這是屏幕截圖 忙碌的貓 ![兩個木偶] [1]

建議您不要存儲圖像名稱,而不是將所有圖像保存在內存中:

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(named:“ imageName”)。

另外,您可以嘗試清理構建文件夾,清理項目並重新安裝該應用程序。 有時在Xcode中復制資源失敗。

請嘗試以下格式

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

您可以改為存儲圖像名稱:

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
}

舉個例子

我不知道到底是什么問題。

但是當我搜索了stackoverflow時。 我在某處讀到Assets.xcassets有問題

然后我得到了錯誤的確切

然后借助該答案解決錯誤。

並希望我解決了錯誤。

同時問題出在資產文件夾中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM