在我的应用程序中,我使用的是PSCollectionView,我想在其中显示文本标签和图像。我对如何使图像和文本居中变得疯狂。我试过这样:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.productImage = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 100, 75)];
self.labelName = [[UILabel alloc]initWithFrame:CGRectMake(10, 80, 100, 20)];
self.labelName.font = [self.labelName.font fontWithSize:12];
self.labelName.textAlignment = NSTextAlignmentCenter;
[self addSubview:self.productImage];
[self addSubview:self.labelName];
self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:236.0f/255.0f alpha:1.0];
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;
self.layer.cornerRadius = 10.0f;
self.layer.borderColor= [[UIColor colorWithRed:207.0f/255.0f green:207.0f/255.0f blue:207.0f/255.0f alpha:1] CGColor];
}
return self;
}
但结果是这样的:
您可以看到文本和图像不在中心,我怎样才能使它们居中?请注意,图像可能有不同的大小。你能帮我找到纠正观点的方法吗?
更新:这是cellForRowMethod
下载图像的方法:
- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView cellForRowAtIndex:(NSInteger)index {
ProductViewCell *cell = (ProductViewCell *)[self.psView dequeueReusableViewForClass:nil];
if (!cell) {
cell = [[ProductViewCell alloc]initWithFrame:CGRectMake(10, 70, 100, 100)];
}
cell.labelName.text = [[self.arrayWithData objectAtIndex:index]objectForKey:@"name"];
NSURL * url = [NSURL URLWithString:[[self.arrayWithData objectAtIndex:index]objectForKey:@"url"]];
[self loadImageFromWeb:url andImageView:cell.productImage];
return cell;
}
- (void) loadImageFromWeb:(NSURL *)urlImg andImageView:(UIImageView *)imageView {
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlImg];
NSString *authCredentials =@"user:password";
NSString *authValue = [NSString stringWithFormat:@"Basic %@",[authCredentials base64EncodedStringWithWrapWidth:0]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage *image = [[UIImage alloc] initWithData:data];
[imageView setImage:image];
} else {
NSLog(@"ERRORE: %@", error);
}
}];
}