UITableViewCell ImageView not scaling properly?

喜夏-厌秋 提交于 2020-01-15 15:30:39

问题


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.

    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
}

回答1:


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

override func layoutSubviews() {
    super.layoutSubviews()

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



回答2:


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))


来源:https://stackoverflow.com/questions/30424799/uitableviewcell-imageview-not-scaling-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!