2015-05-18 134 views
0

我有TableView,我有一个UIImageView和文本。出现表格时布局不正确,但滚动布局时正确。TableView和UIImageView显示不正确的布局,除非滚动

图像异步加载,当加载时添加约束,但直到滚动才更新。

public func tableView 
(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

    { 

       let cell = tableView.dequeueReusableCellWithIdentifier("TimelineCellPhoto", forIndexPath: indexPath) as! TimelineCell 

       cell.photoImageView?.contentMode = .ScaleAspectFit 
       cell.photoImageView?.clipsToBounds = true 

       //IMAGEN 
       var imagen = newNotice.getImage() 
       if(imagen == nil){ 
        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT 
        dispatch_async(dispatch_get_global_queue(priority, 0)) { 
         let url = NSURL(string: newNotice.getImageUrl()) 
         self.getDataFromUrl(url!) { data in 

           imagen = UIImage(data: data!)! 

          dispatch_async(dispatch_get_main_queue()) { 

           cell.setPostedImage(imagen) 
           cell.setNeedsLayout() 
          } 
         } 
        } 
       }else{ 

        cell.setPostedImage(imagen) 
        cell.setNeedsLayout() 
       } 

       cell.postLabel?.text = newNotice.getText() 
       cell.postLabel?.numberOfLines = 0 

       cell.setNeedsLayout() 
      return cell 
     } 
    } 


internal var aspectConstraint : NSLayoutConstraint? { 

     didSet { 

      if oldValue != nil { 
       photoImageView!.removeConstraint(oldValue!) 
      } 
      if aspectConstraint != nil { 
       photoImageView!.addConstraint(aspectConstraint!) 
      } 
     } 
    } 

    override func prepareForReuse() { 
     super.prepareForReuse() 
     aspectConstraint = nil 
    } 
    func setPostedImage(image : UIImage) { 

     let aspect = image.size.width/image.size.height 

     aspectConstraint = NSLayoutConstraint(item: photoImageView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: photoImageView, attribute: NSLayoutAttribute.Height, multiplier: aspect, constant: 0.0) 

     photoImageView!.image = image 
     photoImageView.setNeedsLayout() 
    } 

My tableview it is like this The table Display like this I want like this

+0

尝试重新加载viewDidAppear中的表数据。 – Yanchi

+0

谢谢。但是这个解决方案只有在我已经拥有所有数据的情况下才有效,有时我会在sendAsynchronousRequest中“搜索”信息,所以当应答呼叫时,我会重新载入表以收取数据费用。 – Carol

+0

您是否解决了自动布局问题? –

回答

0

有一个iOS 8的问题,即一个出列tableViewCell的初始宽度将被设置到故事板的单元宽度,而不是tableView宽度。

这会影响初始布局,但单元格会在屏幕上重新出现时正确布置。

(什么是幕后发生的事情是错误的单元格的宽度会影响任何内容查看标签的preferredMaxLayoutWidth。)

一种解决方法是设置单元格的边框宽度,以匹配的tableView的宽度。单元格将从头开始正确布局,无需重新加载或滚动。

您可能还会考虑使用占位符图像,直到图像加载完毕。这将消除必须添加和删除imageView的约束。 AFNetworking可以为您处理异步下载和设置图像。

更新:

看起来你有太多的垂直约束。如果您有3个垂直堆叠物品,则只需要4个垂直约束来放置它们。

但我仍然认为这是一个“宽度”问题,标签有错误preferredMaxLayoutWidth。自动布局认为它最初需要约9行来适应所有文本,但是当单元格在屏幕上滚动时,宽度现在是正确的,并且自动布局意识到它只需要3行。

+0

谢谢,我尝试了,但是如果占位符比图片大,我有一个空间,当滚动修复它时,也许我有错误的限制 – Carol

+0

如果布局最初不正确,但滚动修复它,因为最初的单元格宽度是错误的,这导致标签宽度错误,尝试将单元格的宽度设置为tableView宽度 –

+0

单元格的宽度与表格宽度相同现在我在文本和单元格底部之间有空格。我可以修复图像和文字之间的距离 – Carol