简体   繁体   中英

Unable to Anchor UIImageVIew in UICollectionViewCell (programmatically)

Working on specing out a view in Playground and can't seem to figure out why UIIMageView is being placed in the center of a UICollectionViewCell.

Relevant Code:

class BookCell: UICollectionViewCell {
    
    static let identifier = "bookCell"
    
    override init(frame: CGRect) {
        super.init(frame: .zero)
        self.layer.cornerRadius = 12
        self.backgroundColor = .brown
        addAllSubviews()
        addAllConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var cover: UIImageView = {
        let imageview = UIImageView()
        imageview.translatesAutoresizingMaskIntoConstraints = false
        var largeImage = UIImage(named: "medium.jpg")
        imageview.image = largeImage
        imageview.contentMode = .scaleAspectFit
        //imageview.contentMode = .scaleToFill
        return imageview
    }()
    
    func coverConstraints(){
        NSLayoutConstraint.activate([
            cover.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0),
            
            /**widthConstraint*/
            NSLayoutConstraint(item: cover,
                               attribute: .width,
                               relatedBy: .equal,
                               toItem: self,
                               attribute: .width,
                               multiplier: 1.0, constant: 0.0),

            /**heightConstraint*/
            NSLayoutConstraint(item: cover,
                               attribute: .height,
                               relatedBy: .equal,
                               toItem: self,
                               attribute: .height,
                               multiplier: 0.75, constant: 0.0)
        ])
    }
    
    
    let wordLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "test"
        return label
    }()
    
    func wordLabelConstraints() {
        NSLayoutConstraint.activate([
            wordLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
            wordLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
            wordLabel.topAnchor.constraint(equalTo: cover.bottomAnchor, constant: 2)
        ])
    }

    // MARK: - Add Subviews
    func addAllSubviews() {
        self.addSubview(cover)
        self.addSubview(wordLabel)
    }
    
    // MARK: - SubViews Constraints
    func addAllConstraints() {
        coverConstraints()
        wordLabelConstraints()
    }
}

BookCell is then used in a UICollectionViewController like so:

class ViewController: UIViewController {

    fileprivate let collectionView: UICollectionView = {
        let layout = ColumnFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .blue
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    var data: [Int] = Array(0..<10)

    override func loadView() {
        super.loadView()
        view.addSubview(collectionView)
        
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: view.topAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16)
        ])

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        self.collectionView.register(BookCell.self, forCellWithReuseIdentifier:     BookCell.identifier)
        self.collectionView.alwaysBounceVertical = true
        self.collectionView.backgroundColor = .yellow
    }
}

Result:

在此处输入图像描述

I noticed that using scaleToFill instead of scaleAspectFit results in image covering the entire width of the cell. The result (see image below) fits what I am aiming for but... see question below在此处输入图像描述

Question:

  1. Is using scaleToFill the only way to pin an image to the edges (leading and trailing) of UICollectionViewCell. If so, why is this?
  2. I also tried adding the UIImageView to a UIStackView and I believe I got the same results.
  3. Please note that I am not interested in doing this via Storyboard.

Thank you for providing feedback

There is one more option: .scaleAspectFill but may be cropped your image's content.

The option to scale the content to fill the size of the view.
Some portion of the content may be clipped to fill the view’s bounds.

Think about getting the image size ratio (width/height), you having a fixed width based on superview, and height will be based on the image Ratio.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM