设置UITableViewCell高度与图像成比例

时间:2016-03-11 20:16:06

标签: ios swift

我有1x的图像,大小为320x130。我想将UItableViewCell设置为始终具有此图像的比例。我怎样才能实现这一目标?我试过下面的代码,但似乎使图像非常小?

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {



    let ratio = UIScreen.mainScreen().bounds.width / 130
    let targetHeight = 130 * UIScreen.mainScreen().scale


    return targetHeight / ratio
}

1 个答案:

答案 0 :(得分:0)

您应该使用UIScreen.mainScreen().bounds而不是tableView.bounds,而在您的情况下它是相同的,但如果您更改表格视图,它将无效。

就比例而言,它是这样的:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    return 130.0/320.0 * tableView.bounds.width
}

您可以通过将高度除以宽度来获得比率,然后将其与表格视图的宽度相乘以获得所需的高度。