UICollectionView Cell + UiLabel with AutoLayout

后端 未结 6 753
醉酒成梦
醉酒成梦 2020-12-29 08:14

I\'m trying to pin an UILabel to it\'s parent cell. I added four constraints (top, leading, trailing, bottom) which works fine on iOS 8.0 but not on iOS 7.X

相关标签:
6条回答
  • 2020-12-29 08:46

    Just one more possibility that I found in my project.

    Usually I copy/paste similar objects, but doing that, sometimes, holds the same ID.
    So I fixed my constraint problem by creating an object from scratch.

    0 讨论(0)
  • 2020-12-29 08:50

    Overriding the custom cell's layoutSubviews is a possible workaround:

    override func layoutSubviews() {
        contentView.frame = bounds
        super.layoutSubviews()
    }
    
    0 讨论(0)
  • 2020-12-29 08:51

    UIView:0x798ae5d0 is the contentView of the CollectionViewCell. Somehow at a certain moment it uses the UICollectionViewCells defaultSize, which is (50.0, 50.0).

    <NSAutoresizingMaskLayoutConstraint:0x798a8b00 h=--& v=--& H:[UIView:0x798ae5d0(50)]>
    

    As your horizontal margins 8 + 43 = 51 are bigger than the contentView (50) it is impossible to satisfy the layout.

    <NSLayoutConstraint:0x799573a0 H:|-(8)-[UIView:0x798a86e0]   (Names: '|':UIView:0x798ae5d0 )>
    <NSLayoutConstraint:0x799573d0 H:[UIView:0x798a86e0]-(43)-|  (Names: '|':UIView:0x798ae5d0 )>
    

    One can make the layout more flexible, so that it also works on a (50.0, 50.0) size. In your case by changing equal 43 to <= 43 or by reducing a priority of 1000 to 750 or 999.

    0 讨论(0)
  • 2020-12-29 08:53

    Instead of giving four constraints (top, leading, trailing, bottom). Try top, leading, width and height. It should work.

    0 讨论(0)
  • 2020-12-29 09:06

    I hope you have added constraints to the collection with respect to it's parent (which would be the view of the UIViewController) so that it's width and height is equal to the parent view.

    enter image description here

    0 讨论(0)
  • 2020-12-29 09:13

    The problem is that your custom view (UILabel) has constraints, which conflict with cell's (or better cell's contentView's) constraints. The cell's NSAutoresizingMaskLayoutConstraint are created automatically from what you set in UICollectionView properties in xib (or storyboard) as Cell Size. I have solved my similar problem (*) by explicitly setting

    - (void)awakeFromNib {
    
        [super awakeFromNib];
    
        self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    

    in my custom UICollectionViewCell subclass. This gets rid of cell size constraint set in Storyboard.

    (*) Disclaimer: My collectionView has self sizing cells based on their content view, which is defined by autolayout. I had warnings about conflicting constraints of my content autolayout, and explicit size in Storyboard. This helped me to get rid of those warnings.

    0 讨论(0)
提交回复
热议问题