在UITableViewCell中填充动态图像

时间:2015-10-26 15:29:22

标签: ios swift uitableview autolayout sdwebimage

我正在尝试使用与Instagram完全相同的匿名Feed制作应用。我使用AFNetworking下载JSON数据和SDWebImage来添加和缓存图像。

当我加载可变大小的图像时,我希望表格视图单元格自动调整其高度。

现在的问题是当应用程序加载时,图像显示不正确但在我向下滚动并向后滚动回同一个单元格后,图像会按照我想要的方式自行调整,但图像上方和下方总是有空格

滚动前

enter image description here

滚动后

enter image description here

以下是UIImage视图的约束:

  1. 追踪空间到superview:0
  2. 领导空间到superview:0
  3. 顶部空间:8
  4. 底部空间:8
  5. 将内在大小设置为占位符和内容模式为Aspect Fit。
  6. 这是我的ViewDidLoad方法代码:

     override func viewDidLoad() {
        super.viewDidLoad()
    
        self.navigationController?.navigationBar.barTintColor = UIColor.yellowColor()
    
        feedList = NSMutableArray() 
    
        self.feedTable.rowHeight = UITableViewAutomaticDimension
        self.feedTable.estimatedRowHeight = 200.0
    
        var connection :  CommunicationManager! = CommunicationManager()
    
        //initiate a connection and load feed data
        connection.getFeedData( { (response, error) -> Void in
    
            if(response != nil){
                dispatch_async(dispatch_get_main_queue(), {
    
                    self.feedList = response
                    self.feedTable.hidden = false
                    self.feedTable.reloadData()
                })
    
            }
    
    }
    

    TableView&#39的CellForRowAtIndex:

      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! FeedTableViewCell
    
    
        let feedData : NSDictionary! = feedList[indexPath.row] as! NSDictionary
    
        let imgURL : NSURL! = NSURL(string: feedData.valueForKey("image_name") as! String)
        cell.feedImage.sd_setImageWithURL(imgURL, placeholderImage: UIImage(named: "LoadingImage"))
    
        return cell
    }
    

    我尽力解决这个问题,却无法使其发挥作用。任何人都可以告诉我如何使用故事板解决这个问题。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要调用layoutIfneeded方法:使用以下代码: -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];

[cell.nImageView sd_setImageWithURL:[NSURL URLWithString:[imageUrlArray objectAtIndex:indexPath.row]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    cell.widthConst.constant = image.size.width;
    [cell layoutIfNeeded];
    [cell layoutSubviews];

}];

return cell;

}

如果你想要动态宽度,那么你需要添加固定宽度约束并在块中更新它。

参考屏幕截图image image2

相关问题