如何将服务器中的图像加载到swift 3中的tableView单元格?

时间:2017-01-06 17:26:31

标签: ios json swift uitableview

我正在尝试将新闻加载到tableView中,我做到了。如何将图像加载到标题旁边的tableView单元格?

我希望将图像加载到标题的左侧。

主机:         https://api.sis.kemoke.net/news

图片网址变量:imgUrl

这是我的班级:

import Alamofire //Framework for handling http requests
import UIKit 

/*A class which will process http requests, receive the news as string and fill the array with such data which will be displayed in a table*/
class NewsTableViewController: UITableViewController {
    //Custom struct for the data
    struct News {
        let title : String
        let text : String
        let link : String

        init(dictionary: [String:String]) {
            self.title = dictionary["title"] ?? ""
            self.text = dictionary["text"] ?? ""
            self.link = dictionary["link"] ?? ""
        }
    }

    //Array which holds the news
    var newsData = [News]()

    // Download the news
    func downloadData() {
        Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            //Optional binding to handle exceptions
            self.newsData.removeAll() // clean the data source array
            if let json = response.result.value as? [[String:String]] {
                for news in json {
                    self.newsData.append(News(dictionary: news))
                }
                self.tableView.reloadData()
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadData()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let news = newsData[indexPath.row]
        cell.textLabel?.text = news.title
        return cell
    }
}

2 个答案:

答案 0 :(得分:1)

不知何故,做这样的事情的“最佳实践”是为每个新闻创建一个自定义单元格(UITableViewCell)和一个模型类。这种情况是每个“快速教程网站”都有一些例子。 你可以在这些链接中找到其中一些:

http://www.kaleidosblog.com/swift-uitableview-load-data-from-json

https://grokswift.com/uitableviewcell-images-from-api/

答案 1 :(得分:-1)

斯威夫特3 这段代码是tableview使用imageview中的image和label打印获取api Json解析数据

func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - >的UITableViewCell     {          让cell = tableView.dequeueReusableCell(withIdentifier:“TableViewCell”,for:indexPath)为! TableViewCell

Window.window