UITableViewCell ImageView无法正确缩放?

时间:2015-05-24 14:49:30

标签: ios uitableview swift ios8

我正在使用用户选择的图片填充UITableView。我希望表格单元格中的缩略图都具有相同的大小,而不影响纵横比,以免拉伸/歪斜图像,这听起来像ScaleAspectFill,但UIViewContentMode都没有选择似乎有效果。我有相互矛盾的方法,值得注意的是heightForRowAtIndexPath,但删除它会使我的细胞太小。以下是我的didSelectRowAtIndexPathheightForRowAtIndexPath方法,以及来自我当前代码的模拟器的屏幕截图(使用模拟器库存图像)。任何帮助表示赞赏。 screenshot from iOS simulator

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //sets cell based on meme in array
    let cell = tableView.dequeueReusableCellWithIdentifier("memeCell") as! UITableViewCell
    let meme = self.memes[indexPath.row]

    // Set the name and image
    cell.textLabel?.text = meme.topText + " " + meme.bottomText
    cell.imageView?.frame = CGRectMake(0, 0, 200, 100)
    cell.imageView?.contentMode = UIViewContentMode.ScaleToFill //ScaleAspectFill is best, ScaleToFill used to exagerate that its not working
    //cell.imageView?.backgroundColor = UIColor.grayColor() //legacy code, will be removed at commit
    cell.imageView?.image = meme.origImage

    return cell
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    //cell row won't be large enough unless this method is called
    return 75.0
}

2 个答案:

答案 0 :(得分:3)

您可以添加UITableViewCell的子类,然后覆盖layoutSubviews方法:

override func layoutSubviews() {
    super.layoutSubviews()

    self.imageView.frame = CGRect(0,0,200,100)
}

答案 1 :(得分:0)

查看https://github.com/mattgemmell/MGImageUtilities

您可以使用UIImage + ProportionalFill中的裁剪功能,按比例缩放图像以完全填充所需尺寸,朝中心裁剪,在分配图像之前将所有图像裁剪为相同尺寸。

你可以像这样使用它:

cell.imageView?.image = meme.origImage. imageCroppedToFitSize(CGSize(width: 200, height: 100))
相关问题