4

I have a UICollectionView which contains some cells.

Each cell holds one UILabel within it. Within the label is one letter, it acts as a tile (as such). When more cells are added to the UICollectionView the UICollectionViewCells change size with the following:

-(CGSize)collectionView:(UICollectionView *)collectionView 
                 layout:(UICollectionViewLayout *)collectionViewLayout 
 sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"%s",__PRETTY_FUNCTION__);

    NSLog(@"the word array count is: %i",self.wordArray.count);
    if (self.wordArray.count <= 5) {
        return CGSizeMake(50,50);
    } else if (self.wordArray.count <= 6 ) {
        return CGSizeMake(30, 30);
    } else if (self.wordArray.count <= 8 ) {
        return CGSizeMake(10, 10);
    } else {
        return CGSizeMake(100,100);
    }

}

What I am trying to do now is re-size the UILabel within the cell each time the layout is changed. How can I fit the labels size to the cells size using AutoLayout? Also how can I update the font size based on the UILabel size?

4

2 回答 2

0

You can set something like the following layout constraints:

NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(label);
NSDictionary *insetMetrics = @{
    @"left" : @(10.0f),
    @"right" : @(10.0f),
    @"top" : @(10.0f),
    @"bottom" : @(10.0f)
};

[cell addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(left)-[label]-(right)-|" options:kNilOptions metrics:insetMetrics views:viewDictionary]];
[cell addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(top)-[label]-(bottom)-|" options:kNilOptions metrics:insetMetrics views:viewDictionary]];

Text in a UILabel can automatically shrink if you set the correct properties (see the UILabel Class Reference). So if you set the font size initially to the size you'd like for the largest cell, as the label shrinks, the text will shrink with it.

于 2013-08-19T15:30:23.057 回答
0

Re-creating this in IB worked. I was able to set the constraints for the horizontal/vertical to 0/required for the sides of the label in the cell itself and this worked.

于 2013-08-21T21:47:53.983 回答