如何使用.scaleAspectFit和.top在UIImageView中正确对齐图像?

时间:2019-06-24 09:30:42

标签: ios swift uiimageview uistackview

在使用UIImageView的同时,我似乎找不到一种将图像对准此.scaleAspectFit顶部的方法。我以蓝色突出显示了ImageView,以便您可以看到发生了什么。如您所见,图像垂直居中,但我要求将其固定在顶部。我可以在.scaleAspectFit里面同时设置UIStackView和.top吗?

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))

}
}

1 个答案:

答案 0 :(得分:0)

我也很好奇是否有人对此问题有建议。