Chris Hansen
Chris Hansen

Reputation: 8687

how to set the size of an imageView inside table view cell

I set the imageView property on a tableView cell. I want to change the width and height of the image. How can I do so without using a custom cell? Here's my code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = options[stepIndex][indexPath.row]
    cell.textLabel?.font = UIFont(name: "Inter-Regular", size: 18)
        
    let iconImage = UIImage(named: optionIcons[stepIndex][indexPath.row])
    if stepIndex == 0 {
            cell.imageView?.sd_setImage(with: URL(string: optionIcons[stepIndex][indexPath.row]), placeholderImage: UIImage(named: "icon-history"))
    } else {
        cell.imageView?.image = iconImage
    }
    cell.imageView?.tintColor = .systemBlue

    // Update checkbox state
    if selectedOptions.contains(options[stepIndex][indexPath.row]) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }
        
    return cell
}

Upvotes: -3

Views: 61

Answers (2)

THEJAS
THEJAS

Reputation: 109

I'm not sure whether this works or not. Try this table view delegate method.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    
    cell.imageView?.layer.contentsScale = 0.6 // change as per your needs
}

You can choose different scale for different cell as well using indexPath.row

Or

you can use layoutMargins. Somewhat like content insets for collection views. In case of collection view we'll have a separate delegate method to choose size. But for table view we don't have them. Need to find other ways like this.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

// Set layout margins for the cell itself
cell.layoutMargins = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)

// OR

// Set layout margins for the contentView
cell.contentView.layoutMargins = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)

return cell

}

Upvotes: -1

matt
matt

Reputation: 535890

Do not speak, in your code, in terms of the textLabel or the imageView at all. They are deprecated. Instead, get the cell's defaultContentConfiguration and populate the cell using the UIListContentConfiguration's imageProperties. If you set the imageProperties's maximumSize, all the right things will happen (unless your image is just too darned small to begin with, but that's easily fixed).

You will also need to set the label using the configuration's text and textProperties.

Upvotes: 0

Related Questions