我有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()
}
尝试重新加载viewDidAppear中的表数据。 – Yanchi
谢谢。但是这个解决方案只有在我已经拥有所有数据的情况下才有效,有时我会在sendAsynchronousRequest中“搜索”信息,所以当应答呼叫时,我会重新载入表以收取数据费用。 – Carol
您是否解决了自动布局问题? –