基于视图的中心标签

时间:2019-03-12 04:14:28

标签: ios swift uiview uicollectionview nslayoutconstraint

我想基于视图居中放置标签。标签位于collectionView内,我想基于运行时在collectionView内的视图将该标签居中。

我试图做的是将标签约束的constant更改为视图的帧MidY,但是它不起作用:

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

以下是屏幕:

enter image description here

这是情节提要:

enter image description here

这是我的收藏查看代码

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

这是我的手机代码

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

请查看代码// THIS DOES NOT WORK.中的注释,有任何建议吗?

0 个答案:

没有答案