显示表格内的图像时出错!斯威夫特 3
Posted
技术标签:
【中文标题】显示表格内的图像时出错!斯威夫特 3【英文标题】:Error to show the image inside the table! Swift 3 【发布时间】:2017-03-17 02:22:29 【问题描述】:我正在获取图像的 url 并传递给 transform 和 image 并成为 在表格的单元格内创建,但是这返回我的错误说它是空的!
请有人帮助我!
这是我的两门课。
import UIKit
var margemPadrao : CGFloat = 10.0
var alturaNavBar : CGFloat = 0.0
var alturaStatusBar:CGFloat = UIApplication.shared.statusBarFrame.size.height
var alturaTela : CGFloat = 0.0
var larguraTela : CGFloat = 0.0
var alturaCelula : CGFloat = 0.0
var listaCardNovidades:[Novidades] = []
class NewsScreenViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
@IBAction func menuButtonTapped(_ sender: UIBarButtonItem)
toggleSideMenuView()
var minhaTabela:UITableView = UITableView()
var meuActivityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
override func viewDidLoad()
super.viewDidLoad()
buscaJSON()
alturaTela = UIScreen.main.bounds.height
larguraTela = UIScreen.main.bounds.width
alturaNavBar = (self.navigationController?.navigationBar.frame.height)!
//pegando a cor da view para ser igual na tabela
let corViewbackground:UIColor = self.view.backgroundColor!
//setando o frame da tabela com altura largura e posicionamentos
minhaTabela.frame = CGRect(x: 0, y: 0, width: larguraTela, height: alturaTela)
meuActivityIndicator.frame = minhaTabela.frame
minhaTabela.delegate = self
minhaTabela.dataSource = self
//backgroundo color da tabela
minhaTabela.backgroundColor = corViewbackground
//retirando as linhas da tabela
minhaTabela.separatorStyle = UITableViewCellSeparatorStyle.none
minhaTabela.register(CelulaCard.self, forCellReuseIdentifier: "CelularCard")
minhaTabela.scrollsToTop = false
meuActivityIndicator.startAnimating()
meuActivityIndicator.hidesWhenStopped = true
self.view.addSubview(minhaTabela)
minhaTabela.isHidden = true
self.view.addSubview(meuActivityIndicator)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return listaCardNovidades.count
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let celula = minhaTabela.dequeueReusableCell(withIdentifier: "CelularCard", for: indexPath) as! CelulaCard
celula.textoTitulo.text = listaCardNovidades[indexPath.row].titulo
//celula.self.caminhoImagem = listaCardNovidades[indexPath.row].imagem
celula.self.caminhoImagem = listaCardNovidades[indexPath.row].imagem
return celula
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
return alturaCelula
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
minhaTabela.deselectRow(at: indexPath, animated: true)
/*FUNÇÃO PARA CARREGAR O JSON*/
func buscaJSON()
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let urlApi = "https://www.floratilemevidencia.com.br/wp-json/wp/v2/download?filter[pagina]=ultimas-novidades"
if let url = URL(string: urlApi)
session.dataTask(with: url, completionHandler: (data, response, error) -> Void in
if error != nil
print("The error is: \(error!)")
return
else if let jsonData = data
do
let parsedJSON = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [[String:AnyObject]]
//print(parsedJSON)
for json in parsedJSON
guard let dados = json["title"] as? [String:AnyObject] else return
let n = Novidades()
n.titulo = dados["rendered"] as! String
n.imagem = json["thumbnail_pdf"] as! String
n.arquivo = json["arquivo"] as! String
listaCardNovidades.append(n)
DispatchQueue.main.async
self.minhaTabela.isHidden = false
self.minhaTabela.reloadData()
self.meuActivityIndicator.stopAnimating()
// for item in listaCardNovidades
// print (item.arquivo)
// print (item.imagem)
// print (item.titulo)
// print ("-------------------------------------------")
//
catch let error as Error
print(error.localizedDescription)
).resume()
//Second Class
import UIKit
class CelulaCard: UITableViewCell
var caminhoImagem:String = ""
var imagemPdfWebView:UIImageView = UIImageView()
var textoTitulo:UILabel = UILabel()
var fundoCard:UIView = UIView()
var indicador:UIActivityIndicatorView = UIActivityIndicatorView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.backgroundColor = UIColor(red: 0.236424, green: 0.610663 , blue: 0.374416, alpha: 1)
fundoCard.frame = CGRect(
x: margemPadrao,
y: margemPadrao,
width: larguraTela-2*margemPadrao,
height: 360
)
fundoCard.backgroundColor = UIColor.white
fundoCard.layer.cornerRadius = 8.0
imagemPdfWebView.frame = CGRect(
x: fundoCard.frame.minX+margemPadrao,
y: fundoCard.frame.minY+margemPadrao,
width: fundoCard.frame.size.width-2*margemPadrao,
height: fundoCard.frame.size.height-6*margemPadrao
)
self.indicador.frame = self.imagemPdfWebView.frame
indicador.startAnimating()
indicador.hidesWhenStopped = true
textoTitulo.frame = CGRect(
x: imagemPdfWebView.frame.minX,
y: imagemPdfWebView.frame.maxY+5,
width: imagemPdfWebView.frame.size.width,
height: 20
)
alturaCelula = fundoCard.frame.size.height+2*margemPadrao+20
textoTitulo.textAlignment = .center
textoTitulo.textColor = UIColor.darkGray
textoTitulo.font = UIFont(name: "Arial", size: 17)
imagemPdfWebView.backgroundColor = UIColor.clear
imagemPdfWebView.contentMode = .scaleAspectFit
imagemPdfWebView.clipsToBounds = true
//Para mudar a cor de quando é selecionado
let bgColorView:UIView = UIView()
bgColorView.backgroundColor = UIColor.black
self.selectedBackgroundView = bgColorView
/*teste*/
print("AKI ->\(caminhoImagem)")
self.addSubview(fundoCard)
self.addSubview(indicador)
self.addSubview(imagemPdfWebView)
self.addSubview(textoTitulo)
carregarImagemUrl(imageUrl: caminhoImagem)
required init?(coder aDecoder: NSCoder)
fatalError("init(coder:) has not been implemented")
override func layoutSubviews()
super.layoutSubviews()
// let urlImagem : URL = URL(string: caminhoImagem)!
// let net:NetworkService = NetworkService(url: urlImagem)
//
// net.downloadImage (imageData) in
// var minhaImg:UIImage = UIImage(data: imageData)!
// DispatchQueue.main.async
// self.imagemPdfWebView.image = minhaImg
//
//
func carregarImagemUrl(imageUrl:String)
let url = URL(string: imageUrl)!
let task = URLSession.shared.dataTask(with: url) (responseData, responseUrl, error) -> Void in
if let imageData = responseData
DispatchQueue.main.async(execute: () -> Void in
self.imagemPdfWebView.image = UIImage(data : imageData)
)
task.resume()
// let url = URL(string: self.caminhoImagem)
// let data = NSData(contentsOf:url!)
//
// // It is the best way to manage nil issue.
// if (data?.length)! > 0
// self.imagemPdfWebView.image = UIImage(data:data! as Data)
// else
// // In this when data is nil or empty then we can assign a placeholder image
// print("Não foi possível ERRO")
//
【问题讨论】:
为什么不使用 SDWebImage 或 Alamofire 来做到这一点? 如何在我的代码中实现 alamofire? 查看raywenderlich.com/147086/alamofire-tutorial-getting-started-2 这是从一个类到另一个类的正确调用吗? var caminhoImagem:String = "" 【参考方案1】:我认为首先您需要正确注册自定义单元格。
var nibName = UINib(nibName: "CelularCard", bundle:nil)
self.tableView.register(nibName, forCellReuseIdentifier: "CelularCard")
然后您需要使用图像加载器库通过 url 将图像加载到图像视图中。我推荐使用KFSwiftImageLoader
let imageURL= listaCardNovidades[indexPath.row].imagem
celula.self.caminhoImagem.loadImage(urlString: imageURL)
【讨论】:
以上是关于显示表格内的图像时出错!斯威夫特 3的主要内容,如果未能解决你的问题,请参考以下文章
运行游乐场时出错。找不到合适的目标设备。 (iOS 斯威夫特)