4

I need to add a 1px bottom border to my UICollectionView cells but I can't get it working, I tried the following code but the border doesn't show:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];


    // Configure the cell
    cell.backgroundColor = [UIColor whiteColor];
    cell.titolo.text = arrayt[prova];

    //create the border
    UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height, cell.frame.size.width, 1)];
    bottomBorder.backgroundColor = [UIColor redColor];

    [cell.contentView addSubview:bottomBorder];


    return cell;
}

What could be the problem?

CGRectMake gets (x,y,width,height) as parameter so I can't understand what's wrong on my code

narner
  • 2,908
  • 3
  • 26
  • 63
LS_
  • 6,763
  • 9
  • 52
  • 88

3 Answers3

3

You need to have correct y offset

//create the border
    UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, cell.frame.size.width, 1)];
    bottomBorder.backgroundColor = [UIColor redColor];
AppleDelegate
  • 4,269
  • 1
  • 20
  • 27
1

You should set the frame of the cell to a known (not zero size) value before adding subviews like this. Then, after you have created your view with the correct frame you need to set the autoresizing mask to ensure that the view remains at the bottom of the view (flexible top, flexible width).

Wain
  • 118,658
  • 15
  • 128
  • 151
0

This is not the way to solve this, UIInsets are better way, as shown in this post: https://stackoverflow.com/a/22823146/12652 . But if you still want to follow this way, you need to remove these views afterwards or they will be kept adding to UICollectionViewCell. Considering you also have UIImageView as a childview :

UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, cell.frame.size.width, 1)];
bottomBorder.backgroundColor = [UIColor colorWithRed:162/255.0f green:143/255.0f blue:143/255.0f alpha:1.0f];

for(UIView *view in cell.contentView.subviews){
    if([view isKindOfClass:NSClassFromString(@"UIImageView")])
        continue;
    else{
        [view removeFromSuperview];
    }
}

[cell.contentView addSubview:bottomBorder];
Community
  • 1
  • 1
Özgür
  • 8,077
  • 2
  • 68
  • 66