Set vertical position for UILabel in UICollectionViewCell using UILayoutGuide

234 Views Asked by At

I'm completely new to UILayoutGuide. I'd like to position a UILabel in the middle of the white space below the imageView, which is the superview of both imageView and UILabel (see view hierarchy below).

enter image description here

Normally, I would add another view and set top constraint to UIImageView and bottom constraint to the bottom edge, then center the label both horizonally and vertically to the view.

But I decided to achieve it using UILayoutGuide. Here is my code:

override func awakeFromNib() {
        super.awakeFromNib()
        let topGuide = UILayoutGuide()
        let bottomGuide = UILayoutGuide()
        self.view.addLayoutGuide(topGuide)
        self.view.addLayoutGuide(bottomGuide)
        topGuide.bottomAnchor.constraint(equalTo: title.topAnchor).isActive = true
        bottomGuide.topAnchor.constraint(equalTo: title.bottomAnchor).isActive = true
        self.view.layoutIfNeeded()
}

The result is that my UILabel does not show at all. What am I doing wrong?

1

There are 1 best solutions below

3
On

enter image description here

Follow Steps -

1) Add a imageView with leading,trailing and top constraint = 0 and give aspect ratio to image so it will automatically get size according to cell

enter image description here

2) now add a uiView just below your imageView and give it 0 constraints as trailing, bottom, leading and 0 contraint to image bottom as shown below and make uiView colour as Clear so it won't show up

enter image description here

3) now drag a label in UiView and add it horizontally and vertically centre in UiView container.

enter image description here

and result will be as expected

Please check the following link to download xib file for collectionViewCell

Link - https://drive.google.com/a/erginus.com/file/d/0B2WiGVeE-REPakh3c21rWDlEWUU/view?usp=sharing