ilija.trkulja
ilija.trkulja

Reputation: 147

Center image in ImageView insinde a TableView

How do I center the ImageView inside a TableViewCell ? Whatever I try it is aligned to the left side ...

Here my Code for the Custom Cell Class:

class CustomImageCell: UITableViewCell {

@IBOutlet weak var productImage: UIImageView!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

override func layoutSubviews() {
    super.layoutSubviews()
    // Customize imageView like you need
    
}

}

And here my Code for the TableView (at least the part where the image is gonna be displayed):

    case 0:
           let cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as! CustomImageCell
//            cell.imageView?.contentMode = .scaleAspectFit
            cell.imageView?.image = MachineData.shared.machineImage
            cell.imageView?.addAspectRatioConstraint()
            
            return cell

And here the constraints for the imageview:

Constraints

Constraints 2

Upvotes: 0

Views: 93

Answers (2)

Faysal Ahmed
Faysal Ahmed

Reputation: 7669

The actual issue is related to the reference of the image view. The tableViewCell has a default imageView that can be accessed by cell.imageView. Now you are using default imageView instead of your productImage.

The image view should be productImage, not the imageView.

 cell.productImage.image = MachineData.shared.machineImage

I hope this will fix.

Upvotes: 1

Fabio
Fabio

Reputation: 5648

try to add constraints programmatically like this: first set your imageView translatesAutoresizingMaskIntoConstraints to false

yourImageView.translatesAutoresizingMaskIntoConstraints  = false

after that add your imageView and set constraints with top and bottom:

addSubview(yourImaview)
    yourImaview.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
    yourImaview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5).isActive = true
    yourImaview.widthAnchor.constraint(equalToConstant: 100).isActive = true
    yourImaview.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true

now in the table view controller set heightForRowAt with the sum of the imageView height+bottom and top space:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 190
}

I suppose that you can reply it in storyboard, assign top and bottom constraints with relative space and set heightForRowAt... hope this help

Upvotes: 0

Related Questions