Prevent vertical UIStackView from stretching a subview?

浪子不回头ぞ 提交于 2019-12-08 11:58:20

问题


I have a UITableViewCell with a vertical UIStackView that currently has .alignment = fill and distribution = fill. Inside the stack view, I have a UILabel and a UIImageView.

The label should be left aligned and stretch across the width of the stackview (and it does). The image view has a content mode of aspect fit and should be centered in the middle of the stackview. I thought this was working as I wanted it to until I set a background color on the UIImageView and then realized that while the image itself appears correct (scaled and centered) the view itself stretches across the full width of the stackview (just like the label does).

Is it possible to have the label stretch the width of the stack view but not the image view? Ideally, I'd like the image view to just be the size of the scaled image and not stretch all the way to the edges of the stack view.


回答1:


Make these changes:

  1. Set your stack view's alignment to .center instead of .fill.
  2. Constrain the label's width to equal the stack view's width.
  3. In code, when you set the image view's image, also create an aspect-ratio constraint on the image view, like this:

    class MyCell: UITableViewCell {
        @IBOutlet private var myImageView: UIImageView!
        private var imageViewAspectConstraint: NSLayoutConstraint?
    
        func setImage(_ image: UIImage) {
            myImageView.image = image
    
            imageViewAspectConstraint?.isActive = false
            imageViewAspectConstraint = myImageView.widthAnchor.constraint(
                equalTo: myImageView.heightAnchor,
                multiplier: image.size.width / image.size.height)
            imageViewAspectConstraint!.isActive = true
        }
    }
    

Note that, since cells can be reused, you also have to remove a prior aspect-ratio constraint if there is one. The code I posted uses imageViewAspectConstraint to save the constraint and remove it when the image changes.




回答2:


One approach:

  • calculate appropriate aspect-fit frame for your image

When the user taps on the image view, evaluate the tap position and only take action if the tap is within the aspect-fit frame.


Another approach:

  • calculate appropriate aspect-fit frame for your image
  • embed the UIImageView horizontally centered inside a UILayoutGuide
  • add the UILayoutGuide as the stack view's arranged subview

This will keep your label stretched across the width of the stack view (the cell) and center your image view, allowing you to detect the taps.



来源:https://stackoverflow.com/questions/52650210/prevent-vertical-uistackview-from-stretching-a-subview

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