我正在开发一个iOS应用程序,它将来自服务器的帖子加载到UICollectionView中。集合视图单元格包含一个固定在单元格底部的UIImageView。
每当我启动应用程序并加载集合视图时,所有图像都无法正确加载,但对于最后一个图像,这是正确的尺寸。所有单元格的格式都相同。
我尝试了很多解决方案但到目前为止还没有任何效果。
我怀疑发生的是在设置为每个单元格的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
}
更新:使用@ Michael的建议我发现Cell图像 正确加载..
但是细胞高度被神奇地裁剪了50px ..
故事板编辑器单元格大小
运行时的单元大小
这似乎是个问题,但我还没有找到解决方案。
更新:在奖金还剩两个小时后,我决定将其奖励给@Michael,因为他的回答帮助我进一步调查我的问题,这个问题仍在继续。答案 0 :(得分:3)
首先,使用Debug View Hierarchy按钮在运行时检查表格单元格中的异常。
然后创建单元格的断点并检查您要设置到单元格的UIImage并确保大小正确。如果您将下载的图像分配给局部变量,您也可以快速查看它,看它是否正确。
然后,如果所有这些看似合理,请检查您的自动布局代码是否健全。
通过从情境中删除图像下载来检查。我会这样做:
如果这一切看起来都不错,那么您就知道这些是服务器映像的下载或布局。
答案 1 :(得分:0)
将15:4Ratio更改为常量高度(80px),并将heightForRowAtIndexPath设置为常量高度(250px)