【问题标题】:How to show image view in table view from json如何从json的表格视图中显示图像视图
【发布时间】:2018-01-01 22:06:11
【问题描述】:

要解析 json,我有以下功能

 func single_news(userid: Int) {

        var request = URLRequest(url: URL(string: news_url)!)
        request.httpMethod = "POST"

        //Pass your parameter here
        let postString = "userid=\(userid)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            guard let data = data, error == nil else {
                print("error=(error)")
                return
            }


            let json: Any?

            do
            {

                json = try JSONSerialization.jsonObject(with: data, options: [])
                print("abcnews")
                //here is your JSON
                print(json)
                let jsonValue : NSDictionary = json as! NSDictionary
                self.results = jsonValue.object(forKey: "data") as! [[String:String]]
                self.DiscoveryNewsTableView.delegate = self
                self.DiscoveryNewsTableView.dataSource = self
                self.DiscoveryNewsTableView.reloadData()

//                let _ = getData.shared.getDataForTableView(dict: json)
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }
        }
        task.resume()
    } 

为了获取数据,创建了类

class getData: NSObject {

    var descriptionn : String = ""
    var image : String = ""

//    static let shared = getData()

    func getDataForTableView(results: [[String:String]], index : Int){

        var productArray = [String:String]()
        productArray = results[index]

        descriptionn = productArray["description"]!
        image = productArray["images"]!
    }
}

在表格视图中显示数据

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryNewscell") as! DiscoveryNewsTableViewCell

//        if results.count > 0{
            classObject.getDataForTableView(results: results, index: indexPath.row)
            cell.sneakerImageView.image=filteredsneakernews[indexPath.row].image
                   print("abc image"+classObject.image)
        cell.newsTitle.text = classObject.descriptionn
//        }
        return cell
    }

如何以字符串格式显示图像 .Image(classObject.image) 如何在表格视图中显示图像视图?您可以从此链接下载代码。https://drive.google.com/file/d/1bVQsuSQINSa6YRwZe2QwEjPpU_m7S3b8/view?usp=sharing

【问题讨论】:

    标签: swift api web-services uitableview uiimageview


    【解决方案1】:

    您想要显示一张图片,但您只有该图片的 URL 而没有图片本身,因此您需要下载它,然后显示它。我有一个我经常使用的类,它允许你简单地调用一行来下载和缓存图像,这样你就可以做这样的事情:

    classObject.getDataForTableView(results: results, index: indexPath.row)
    let image_url = filteredsneakernews[indexPath.row].image
    cell.sneakerImageView.loadImageUsingCacheWithUrlString(urlString: image_url!)
    

    为此,您必须复制下面的类并在您的单元类中,例如,您需要将 imageView 类型从标准 UIImageView 更改为 CustomImageView:

    let imageView: CustomImageView!
    

    //

    import UIKit
    
    let imageCache = NSCache<NSString, UIImage>()
    
    class CustomImageView: UIImageView {
    
        var imageUrlString: String?
    
        func loadImageUsingCacheWithUrlString(urlString: String) {
    
            imageUrlString = urlString
    
            if let cachedImage = imageCache.object(forKey: urlString as NSString) {
                self.image = cachedImage
                return
            }
    
            self.image = nil
    
            let url = URL(string: urlString)
            URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
    
                if error != nil { return }
    
                DispatchQueue.main.async {
    
                    if let downloadedImage = UIImage(data: data!) {
    
                        if self.imageUrlString == urlString {
                            if self.imageUrlString != "" {
                                self.image = downloadedImage
                            } else {
                                self.image = nil
                            }
                        }
    
                        imageCache.setObject(downloadedImage, forKey: urlString as NSString)
                    }
                }
    
            }).resume()
        }
    }
    

    【讨论】:

    • cell.sneakerImageView.loadImageUsingCacheWithUrlString(urlString: image_url!)/////这行给出语法错误 //// 错误:'UIImageView'类型的值没有成员'loadImageUsingCacheWithUrlString'跨度>
    • @ajadka 编辑了我的答案
    • 第二个错误.... let imageView: CustomImageView! /////全局'let'声明需要一个初始化表达式
    • @ajadka 这只是一个例子。你需要做同样的事情,但使用你的sneakersImageView。不要实际添加“let imageView: CustomImageView!”
    • 我把这个声明...... .....给我错误///...无法强制解开非可选类型'UIImage'的值
    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多