I have to create a customize UICollectionViewCell to show a image and a name for the image, And on top of the image, there is a frame image which is 2 pixels bigger in width and height than the image. However, no matter what I do, the image seems to be bigger than the frame image. I did the same thing for the table view, and it works perfect.
Here is the code:
//GridCell.h
@interface GridCell : UICollectionViewCell
@property(nonatomic, strong) UILabel *lblName;
@property(nonatomic, strong) UIImageView *image;
@end
//GridCell.m
#import "GridCell.h"
@implementation GridCell
@synthesize image, lblName;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIImage *bg = [UIImage imageNamed:@"borderUIimgLg.png"];
UIImageView *bgImage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, frame.size.width, frame.size.width)];
[bgImage setImage:bg];
[bgImage setContentMode:UIViewContentModeScaleAspectFill];
NSLog(@"BG Image size %f, %f", bgImage.frame.size.width, bgImage.frame.size.height);
UIImageView *contentImage = [[UIImageView alloc] initWithFrame:CGRectMake(2.0, 2.0, frame.size.width-4.0, frame.size.width-4.0)];
[contentImage setContentMode:UIViewContentModeScaleAspectFill];
[contentImage setClipsToBounds:YES];
self.image = contentImage;
[self.contentView addSubview:self.image];
[self.contentView addSubview:bgImage];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(2.0, frame.size.width, frame.size.width - 4.0, 21.0)];
[label setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:11.0]];
[label setTextAlignment:NSTextAlignmentCenter];
[label setBackgroundColor:[UIColor clearColor]];
self.lblName = label;
[self.contentView addSubview:self.lblName];
}
return self;
}
The UICollectionViewCell has a size of 67 x 100, so in the code, the bgImage supposed to be always to be 67 x 67 and its origin is (0,0) and the contentImage supposed to have a frame of (0,0,63,63). By debugging, it seems correct. However, the conentimage always bigger than the bgImage. The original size of the image is 80 x 80 though. I have tried setClipToBounds, setContentViewMode on either the cell.ContentView or the imageView, but none works.
A screenshot about the problem is attached.
Any help is appreciated.
This might have found the answer by now, try:
contentImage.clipsToBounds = YES;
you are using 2 times frame.size.width instead of frame.size.height on the other one
edit, try this:
in the cell, when using initWithFrame methods, use the self.bounds property of the cell. if you init the imageview inside the border use CGRectInset method to initialize the imageview with smaller bounds and set the imageviews center to same as the contentview of the cell
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With