2017-08-30 73 views
-1

我有JSON圖像。致命錯誤:索引超出範圍:Swift

let imagestring : String? = (myData as AnyObject).value(forKey: "Post_mid_image") as? String 

if imagestring != nil{ 
    let imageTrueString = "https://www.zdoof.com/" + imagestring! 
    self.imageStringArray.append(imageTrueString) 
    print(self.imageStringArray) 
} 

當我試圖把它放在表視圖:

let myImage = cell.viewWithTag(30) as! UIImageView 
let myImageString : String? = imageStringArray[indexPath.row] 

if myImageString != nil{ 
    let ImageUrl = URL.init(string: myImageString!) 

    myImage.kf.setImage(with: ImageUrl) 
} 

它顯示如下錯誤:

致命錯誤:索引超出範圍

我的代碼有什麼問題?

+0

你沒」 t發佈你的'numberOfRowsForSectio的代碼n:'方法,但是這裏發生的是你試圖顯示一個並不存在於你的'imageStringArray'中的行。 –

+0

那麼,在這裏做什麼,請幫助 –

+0

你可以發佈的代碼,返回您的表的行數? –

回答

0

你的行數的方法像這樣

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return imageStringArray.count 
    } 

而且使用如果讓避免強行鑄造

if let myImage = cell.viewWithTag(30) as? UIImageView { 
    if let myImageString = imageStringArray[indexPath.row] as? String { 
     let ImageUrl = URL.init(string: myImageString!) 
     myImage.kf.setImage(with: ImageUrl) 

    } 

} 

更新: -

if indexPath.row < imageStringArray.count { 
    if let myImageString = imageStringArray[indexPath.row] as? String { 
     let ImageUrl = URL.init(string: myImageString!) 
     myImage.kf.setImage(with: ImageUrl) 

    } 
} 
+0

它仍然顯示索引超出範圍 –

+0

嘗試更新的答案 –

+0

我想顯示一些評論(其中可能有評論和圖片/只coments)。如果我將寫func tableView(_ tableView:UITableView,numberOfRowsInSection部分:Int) - > Int { return imageStringArray.count }它只顯示有圖像的註釋 –

相關問題