ios - UITableView 内的动态 UIImageView 大小

标签 ios swift uitableview uiimageview autolayout

我想实现一个带有显示图像的自定义 TableViewCell 的 TableView。

为了简单起见,我只是使用自动布局将 UIImageView 放入 tableviewcell 中(如下图所示)。 enter image description here

我想要的是在 UIImageView 中显示图像,但是这些图像尺寸可以是任何尺寸并且不一致(纵向、横向、正方形)...

因此,我希望显示具有固定宽度(设备的宽度)和尊重图像比例的动态高度的图像。我想要这样的东西:
enter image description here

不幸的是我没能达到那个结果。

以下是我的实现方式 -(我使用 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. 设置 UIImageView 的高度自动布局约束
  2. 修改UIImageView的框架

在此处查看方法 1 和 2 的结果: image Image 2

最佳答案

在 Storyboard 中,为您的 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

关于ios - UITableView 内的动态 UIImageView 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32281886/

相关文章:

swift - 无法将类型 'GenericTableViewController<T, U>' 的值分配给类型 'GenericTableViewController<GenericTableViewCell<_>, _>'

ios - 使用两个 IPA 的捆绑 iOS 应用程序

iphone - 创建一个不保存到持久存储的核心数据模型对象

android - 无法在 Android 设备的 Facebook 页面中看到类似选项

ios - swift : How to change navigation controller's height without adding a toolbar

ios - 如何设置一个整数值作为导航栏的标题?

ios - 是否可以自定义触发 UIScrollView 滚动的滑动手势识别?

ios - 如何自定义UIDatePicker并改变文字颜色和背景颜色?

ios - 如何从 Storyboard创建的 UITableView 中拉出 UIView?

uitableview - Swift - 如何对两种单元格类型使用 dequeueReusableCellWithIdentifier? (身份标识)