1

I can't seem to figure out a way to align my image to the top of this UIImageView, while also using .scaleAspectFit. I've highlighted the ImageView in blue so you can see what's happening. As you can see the image is being vertically centered, but I require it to be fixed to the top. Is there a way I can set it to both .scaleAspectFit and .top inside this UIStackView?

class SwipedPageCell: UICollectionViewCell  {

override init(frame: CGRect) {
    super.init(frame: frame)

    setupViews(distribution: .fillProportionally, alignment: .fill, spacing: 0)

    backgroundColor = UIColor.backgroundGrey()

}

let imageScreenshot: UIImageView = {
   let iv = UIImageView()
    iv.image = UIImage(named: "tv-screenshot")
    iv.contentMode = .scaleAspectFit
    iv.clipsToBounds = true
    iv.translatesAutoresizingMaskIntoConstraints = false

    iv.backgroundColor = .blue
    return iv
}()

let logoText: UILabel = {
    let label = UILabel()
    label.attributedText = NSAttributedString(string: "whatsong", attributes: [
        NSAttributedString.Key.kern: -1.0
        ])
    label.font = UIFont(name: "FatFrank", size: 40)
    label.textColor = UIColor(red: 41/255, green: 45/255, blue: 51/255, alpha: 1)
    label.textAlignment = .center
    return label
}()

let subheading: UILabel = {
    let label = UILabel()
    label.attributedText = NSAttributedString(string: "Discover music from the latest movies and television shows", attributes: [
        NSAttributedString.Key.kern: -0.6
        ])
    label.font = UIFont(name: "Montserrat-SemiBold", size: 16)
    label.textColor = UIColor(red: 41/255, green: 45/255, blue: 51/255, alpha: 1)
    label.numberOfLines = 0
    label.textAlignment = .center
    return label
}()

func setupViews(distribution: UIStackView.Distribution, alignment: UIStackView.Alignment, spacing: CGFloat)   {

    let verticalStackView = VerticalStackView(arrangedSubviews: [imageScreenshot, logoText, subheading])
    verticalStackView.spacing = spacing
    verticalStackView.distribution = distribution
    verticalStackView.alignment = alignment

    addSubview(verticalStackView)

    verticalStackView.anchor(top: topAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 0, left: 20, bottom: 10, right: 20))

}
}
unicorn_surprise
  • 951
  • 2
  • 21
  • 40
  • 1
    Quick google search for `uiimageview aspect fit align top` shows lots of answers out there... You should be able to find one you like. – DonMag Jun 24 '19 at 12:54

0 Answers0