fab*_*ice 21 uitableview uiimageview ios autolayout swift
我想用一个显示图像的Custom TableViewCell实现一个TableView.
为了简单起见,我简单地使用autolayout将UIImageView放在tableviewcell中(如下图所示).

我想要的是在UIImageView中显示图像,但是那些图像尺寸可以是任何东西并且是不一致的(肖像,风景,方形)......
因此,我希望显示具有固定宽度(设备宽度)的图像和相对于图像比例的动态高度.我想要这样的东西:

遗憾的是,我无法达到这一结果.
以下是我实现它的方式 - (我使用Haneke从URL加载图像 - 存储在Amazon S3中的图像):
class TestCellVC: UITableViewCell {
    @IBOutlet weak var selfieImageView: UIImageView!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    func loadItem(#selfie: Selfie) {        
        let selfieImageURL:NSURL = NSURL(string: selfie.show_selfie_pic())!
        self.selfieImageView.hnk_setImageFromURL(selfieImageURL, placeholder: nil, format: HNKFormat<UIImage>(name: "original"), failure: {error -> Void in println(error)
            }, success: { (image) -> Void in
                // Screen Width
                var screen_width = UIScreen.mainScreen().bounds.width
                // Ratio Width / Height
                var ratio =  image.size.height / image.size.width
                // Calculated Height for the picture
                let newHeight = screen_width * ratio
                // METHOD 1
                self.heightConstraint.constant = newHeight
                // METHOD 2
                //self.selfieImageView.bounds = CGRectMake(0,0,screen_width,newHeight)
                self.selfieImageView.image = image
            }
        )
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Register the xib for the Custom TableViewCell
        var nib = UINib(nibName: "TestCell", bundle: nil)
        self.tableView.registerNib(nib, forCellReuseIdentifier: "TestCell")
        // Set the height of a cell dynamically
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 500.0
        // Remove separator line from UITableView
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        loadData()
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("TestCell") as TestCellVC
        cell.loadItem(selfie: self.selfies_array[indexPath.row])
        // Remove the inset for cell separator
        cell.layoutMargins = UIEdgeInsetsZero
        cell.separatorInset = UIEdgeInsetsZero
        // Update Cell Constraints
        cell.setNeedsUpdateConstraints()
        cell.updateConstraintsIfNeeded()
        cell.sizeToFit()
        return cell
    }
}
我对动态高度的计算是正确的(我打印过它).我已经尝试了两种方法(在代码中描述),但它们都没有工作:
请参见方法1和2的结果:
 

sas*_*ash 16
在故事板中添加尾随,前导,下限和上限约束UIImageView.加载图像后,您需要做的就是为您的图像添加一个方面约束UIImageView.您的图像单元格看起来像这样:
class ImageTableViewCell: UITableViewCell {
    @IBOutlet weak var customImageView: UIImageView!
    internal var aspectConstraint : NSLayoutConstraint? {
        didSet {
            if oldValue != nil {
                customImageView.removeConstraint(oldValue!)
            }
            if aspectConstraint != nil {
                customImageView.addConstraint(aspectConstraint!)
            }
        }
    }
    override func prepareForReuse() {
        super.prepareForReuse()
        aspectConstraint = nil
    }
    func setCustomImage(image : UIImage) {
        let aspect = image.size.width / image.size.height
        let constraint = NSLayoutConstraint(item: customImageView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: customImageView, attribute: NSLayoutAttribute.height, multiplier: aspect, constant: 0.0)
        constraint.priority = 999
        aspectConstraint = constraint
        customImageView.image = image
    }
}
您可以在此查看DynamicTableWithImages的工作示例
Jac*_*ack 11
将图像加载到tableView中时,每个图像可以具有不同的宽高比.使用SDWebImage,我们可以从url获取图像 -
 testImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: { (downloadedImage, error, cache, url) in
            print(downloadedImage?.size.width)//prints width of image
            print(downloadedImage?.size.height)//prints height of image
        })
在UITableViewCell设置的ImageView为约束top,bottom,leading,trailing,fixed height constraint999优先级和改变height-constraint-constant根据图像.
 var cellFrame = cell.frame.size
 cellFrame.height =  cellFrame.height - 15
 cellFrame.width =  cellFrame.width - 15
 cell.feedImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: { (theImage, error, cache, url) in
            cell.feedImageHeightConstraint.constant = self.getAspectRatioAccordingToiPhones(cellImageFrame: cellFrame,downloadedImage: theImage!)
        })
计算单元框架并根据它找到相应的高度.
  func getAspectRatioAccordingToiPhones(cellImageFrame:CGSize,downloadedImage: UIImage)->CGFloat {
        let widthOffset = downloadedImage.size.width - cellImageFrame.width
        let widthOffsetPercentage = (widthOffset*100)/downloadedImage.size.width
        let heightOffset = (widthOffsetPercentage * downloadedImage.size.height)/100
        let effectiveHeight = downloadedImage.size.height - heightOffset
        return(effectiveHeight)
    }
从 imageView 中删除高度限制。选择以“方面”开头的图像视图的内容模式,例如:方面填充或方面适合(因为它适合您的要求)。
注意:您还需要设置行的高度,以便 imageView 适合它。使用
heightForRowAtIndexPath
设置自定义行高。
| 归档时间: | 
 | 
| 查看次数: | 17457 次 | 
| 最近记录: |