我正在开发一个将服务器上的帖子加载到UICollectionView中的iOS应用程序.收集视图单元格包含固定在单元格底部的UI
ImageView.
无论何时启动应用程序并加载集合视图,所有图像都无法正确加载,但最后一个图像的尺寸是正确的.所有单元格的格式相同.
我已经尝试了许多解决方案,但迄今没有任何工作.
我怀疑发生的是,在设置为每个单元格的UIImageView之前,图像尚未完成加载(在本例中为最后一个除外).这似乎不可能,因为在获得成功的响应之后重新加载单元格.
这是我特定功能的代码(使用Alamofire)
func getAllPosts(){
let url = "\(Constants.baseURL)/posts/"
let parameters = ["user_id": "\(userProfile!.getId())"]
Alamofire.request(.POST,url,parameters: parameters,encoding: .JSON)
.validate(contentType: ["application/json"])
.responseString { response in
switch response.result {
case .Success:
var postsArray = Array<[String: AnyObject]>()
do {
let json = try NSJSONSerialization.JSONObjectWithData(response.data!,options: NSJSONReadingOptions.MutableContainers)
for post in json as! [AnyObject] {
postsArray.append(post as! [String: AnyObject])
}
//invert array of posts so that latest load first!
postsArray = postsArray.reverse()
} catch {
}
//convert json to Post objects and reload the view
self.initialisePosts(postsArray)
self.collectionView?.reloadData()
case .Failure(let error):
print(error)
}
}
}
所有的帮助是赞赏.
编辑:以下是UIImageView当前的限制
编辑2:这是格式化单元格的代码
override func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// get a reference to our postcell with no image
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifiers[0],forIndexPath: indexPath) as! PostCell
guard let _: Post? = posts[indexPath.row] else {
return cell
}
return configurePostCell(cell,post: posts[indexPath.row])!
}
func configurePostCell(cell: UICollectionViewCell,post: Post) -> PostCell?{
if let cell = cell as? PostCell {
cell.author.text = post.user_name
cell.date.text = formatter.stringFromDate(post.pub_date!)
cell.desc.text = post.desc
cell.layer.cornerRadius = 5 //set corner radius here
cell.advertimage.image = post.advert?.advert_image
return cell
}
return nil
}
更新:使用@迈克尔的建议我发现单元格图像正确加载..
但是细胞高度被神秘地裁减了50像素
故事板编辑器单元格大小
运行时的单元大小
这似乎是一个问题,但我还没有找到解决方案.
更新:剩下两个小时的赏金我决定把它授予@迈克尔,因为他的回答帮助我进一步调查我的问题,这仍然在进行中.
解决方法
首先,使用Debug View Hierarchy按钮在运行时检查表格单元格中的异常.
然后断开单元格创建并检查您将要设置到单元格的UIImage,并确保大小正确.如果将您下载的映像分配给本地变量,您可能也可以快速查看它,看看它是否正确.
那么,如果所有这些似乎都是明智的,那么检查你的自动布局代码是否健壮.
通过从这种情况下删除图像的下载来检查.我会这样做:
>删除图像的设置,但将图像背景设置为UIColor.Red或某些东西,并检查它们的布局很好,比普通的UIViews少.
>将应用程序包中的图像作为PNG嵌入,而不是下载的图像.再次,看看它如何呈现.
>在应用程序包中尝试不同大小的图像,然后再次检查(如果相关 – 可能所有图像的大小都相同)
如果这一切都看起来不错,那么你知道这些服务器映像的下载或布局.