Center Label Based on View

2019-07-26 20:31发布

问题:

I want to center a label based on a view. The label is inside a collectionView and I want to center this label based on a view that is NOT inside the collectionView at runtime.

What I tried to do is change the constant of the label's constraint to the view's frame midY but it doesn't work:

// THIS DOES NOT WORK. I want the `textLabel` centered inside the `yellowView`.
cell.textLabelCenterYVerticalConstraint.constant = yellowView.frame.midY

Here is the screen:

Here is the Storyboard:

This is my collectionView code

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var yellowView: UIView!

    let imageName = ["1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5)
    }
}

// MARK: - UICollectionViewDataSource

extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageName.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! MyCollectionViewCell
        let index = indexPath.row
        let images = imageName[index]
        cell.backgroundImageView.image = UIImage(named: images)

        // THIS DOES NOT WORK. I want the `textLabel` centered inside the `yellowView`.
        cell.textLabelCenterYVerticalConstraint.constant = yellowView.frame.midY

        return cell
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.bounds.width, height: collectionView.bounds.height)

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10.0
    }
}

This is my cell code

class MyCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var backgroundImageView: UIImageView!
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet weak var textLabelCenterYVerticalConstraint: NSLayoutConstraint!
}

Please see the comment in the code // THIS DOES NOT WORK. Any suggestions?