我正在尝试通过自动调整图像大小来获取tableview单元格。基本上,我希望单元格中的图像宽度总是相同,并且高度要根据图像的长宽比而变化。
我创建了一个单元格类,该类仅具有标签的出口,imageView和用于图像高度的NSLayoutConstraint。我有一些异步方法来下载图像并将其设置为单元格imageView的图像。然后调用完成句柄,然后运行以下代码将高度约束调整为正确的高度:
cell.cellPhoto.loadImageFromURL(url: photos[indexPath.row].thumbnailURL, completion: {
// Set imageView height to the width
let imageSize = cell.cellPhoto.image?.size
let maxHeight = ((self.tableView.frame.width-30.0)*imageSize!.height) / imageSize!.width
cell.cellPhotoHeight.constant = maxHeight
cell.layoutIfNeeded()
})
return cell
这是我编写的加载图像的UIImageView扩展:
func loadImageFromURL(url: String, completion: @escaping () -> Void) {
let url = URL(string: url)
makeDataRequest(url: url!, completion: { data in
DispatchQueue.main.async {
self.image = UIImage(data: data!)
completion()
}
})
}
以及它调用的makeDataRequest函数:
func makeDataRequest(url: URL, completion: @escaping (Data?) -> Void) {
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: { data, response, error in
if error == nil {
let response = response as? HTTPURLResponse
switch response?.statusCode {
case 200:
completion(data)
case 404:
print("Invalid URL for request")
default:
print("Something else went wrong in the data request")
}
} else {
print(error?.localizedDescription ?? "Error")
}
})
task.resume()
}
这适用于所有超出帧的单元格,但是帧中的单元格中的图像视图很小。只有当我向下滚动然后再次向上备份时,它们的大小才正确。我该如何解决?我知道其他人也遇到了这个问题,但是尝试进行修复无济于事。
我不得不重新创建问题以了解发生了什么。基本上,您需要重新加载表视图。图片下载完成后,我将执行此操作。
在具有表视图var的视图控制器中。将此添加到viewDidLoad()
功能。
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
//Create a notification so we can update the list from anywhere in the app. Good if you are calling this from an other class.
NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "loadList"), object: nil)
}
//This function updates the cells in the table view
@objc func loadList(){
//load data here
self.tableView.reloadData()
}
现在,在完成照片下载后,您可以使用以下方法通知视图控制器重新加载表格视图,
func loadImageFromURL(url: String, completion: @escaping () -> Void) {
let url = URL(string: url)
makeDataRequest(url: url!, completion: { data in
DispatchQueue.main.async {
self.image = UIImage(data: data!)
completion()
//This isn't the best way to do this as, if you have 25+ pictures,
//the list will pretty much freeze up every time the list has to be reloaded.
//What you could do is have a flag to check if the first 'n' number of cells
//have been loaded, and if so then don't reload the tableview.
//Basically what I'm saying is, if the cells are off the screen who cares.
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loadList"), object: nil)
}
})
}
我的代码如下,我没有像您那样做缩放比例的事情,但是同样的想法适用。这就是您如何重新加载表格视图的方法。另外,我个人不喜欢编写自己的下载代码,状态代码和所有内容。这不好玩,为什么别人做完后重新发明轮子呢?
Podfile
pod 'SDWebImage', '~> 5.0'
mCell.swift
class mCell: UITableViewCell {
//This keeps track to see if the cell has been already resized. This is only needed once.
var flag = false
@IBOutlet weak var cellLabel: UILabel!
@IBOutlet weak var cell_IV: UIImageView!
override func awakeFromNib() { super.awakeFromNib() }
}
viewController.swift(单击以查看完整的代码)我将在此处提供代码的重点。
//Set the image based on a url
//Remember this is all done with Async...In the backgorund, on a custom thread.
mCell.cell_IV.sd_setImage(with: URL(string: ViewController.cell_pic_url[row])) { (image, error, cache, urls) in
// If failed to load image
if (error != nil) {
//Set to defult
mCell.cell_IV.image = UIImage(named: "redx.png")
}
//Else we got the image from the web.
else {
//Set the cell image to the one we downloaded
mCell.cell_IV.image = image
//This is a flag to reload the tableview once the image is done downloading. I set a var in the cell class, this is to make sure the this is ONLY CALLED once. Otherwise the app will get stuck in an infinite loop.
if (mCell.flag != true){
DispatchQueue.main.asyncAfter(deadline: .now() + 0.025){ //Nothing wrong with a little lag.
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loadList"), object: nil)
mCell.flag = true
}
}
}
}