UITableViewCell ImageView not scaling properly?

2019-08-05 19:06发布

I am populating a UITableView with images selected by the user. I'd like to the have thumbnails in the table cells all be the same size without affecting the aspect ratio so as not to stretch/skew the images, which sounds to me like ScaleAspectFill, however none of the UIViewContentMode selections seem to have an effect. There me conflicting methods, notable heightForRowAtIndexPath, but removing this makes my cells too small. The following are my didSelectRowAtIndexPath and heightForRowAtIndexPath methods, along with a screen shot from the simulator of my current code (using simulator stock images). Any help is appreciated. 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条回答
smile是对你的礼貌
2楼-- · 2019-08-05 19:20

You can add a subclass of UITableViewCell, then overrides layoutSubviews method:

override func layoutSubviews() {
    super.layoutSubviews()

    self.imageView.frame = CGRect(0,0,200,100)
}
查看更多
神经病院院长
3楼-- · 2019-08-05 19:28

Check out https://github.com/mattgemmell/MGImageUtilities

You can use the crop function in UIImage+ProportionalFill, that scales the image proportionally to completely fill the required size, cropping towards its center, to crop all images to the same size before assigning the image.

You can use it like this:

cell.imageView?.image = meme.origImage. imageCroppedToFitSize(CGSize(width: 200, height: 100))
查看更多
登录 后发表回答