2017-08-10 39 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選項卡。檢查目標會員部分,應該有你的目標名稱附近的複選標記 –

相關問題