0

I have UITableView, where is a UIStackView with same views(different content only) on each cell.(The tableView's cell is shown below)

UITableView cell

The view consists of UIImageView and UILabel above. The UIImageView's content is set to .scaleAspectFit, because of keeping ratio. I have a problem with adding a new image layer (subview) to imageView, which has to perfectly overlap current image, but I can't fit on image properly with autolayout, because I know only UIImageView's anchor, not image's anchor (it doesn't exists).

PS: I have tried to use imageview.image.size.width, to set width and height, but it's also useless.

Current code of adding subview using autolayout:

func addStripe(){
        let stripeLayer = UIImageView(image: #imageLiteral(resourceName: "book_new"))
        imageView.addSubview(stripeLayer)

        stripeLayer.contentMode = .scaleToFill
        stripeLayer.translatesAutoresizingMaskIntoConstraints = false

        stripeLayer.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true
        stripeLayer.leadingAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true
        stripeLayer.trailingAnchor.constraint(equalTo: imageView.trailingAnchor).isActive = true

Aaaand there is a result of addStripe function (the wrong one)

And there is a result

Thanks everyone for your time!

preneond
  • 497
  • 2
  • 5
  • 21
  • 1
    Please have a look at [this](https://stackoverflow.com/questions/6278876/how-to-know-the-image-size-after-applying-aspect-fit-for-the-image-in-an-uiimage/43114960#43114960). It tells you how you get the resulting size of your image. It should then be easy to play you stripe correctly. – Reinhard Männer Sep 21 '17 at 19:02
  • @ReinhardMänner It works perfectly! Please add your comment as an answer, because of marking it as a solution. Thank you very much. – preneond Sep 21 '17 at 19:25

2 Answers2

1

I think you should set frame of your stripeLayer equal to imageView. You can do this with init method of UIImageView like this:

let stripeLayer = UIImageView(frame: imageView.frame)
stripeLayer.image = #imageLiteral(resourceName: "book_new")
imageView.addSubview(stripeLayer.image)

I hope it help you

p.yarandi
  • 59
  • 1
  • 11
0

@ReinhardManner's comment helped me and it works. This single line fix my problem

let sizeInView = AVMakeRect(aspectRatio: imgViewFake.image.size, insideRect: imgViewFake.bounds).size
preneond
  • 497
  • 2
  • 5
  • 21