UILabel背景图像与UICollectionViewCell相同的宽度标签大小

时间:2013-12-17 17:47:23

标签: ios image background uilabel

我一直在网上搜索几天但找不到任何解决方案。

最后弄明白该怎么做:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

   NSString *cellIdentifier=@"Cell";
   SampleImageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
   cell.sampleImageView.image=[UIImage imageNamed:[sampleImageList objectAtIndex:indexPath.row]];
   cell.sampleTitleLabel.text=[sampleTitleArray objectAtIndex:indexPath.row];

   UIImage *img = [UIImage imageNamed:@"sample.png"];
   CGSize imgSize = cell.sampleTitleLabel.frame.size;

   CGSize maximumLabelSize = CGSizeMake(319,9999);
   CGSize expectedLabelSize = [cell.sampleTitleLabel.text sizeWithFont:cell.recipeTitleLabel.font
                                  constrainedToSize:maximumLabelSize
                                      lineBreakMode:cell.sampleTitleLabel.lineBreakMode];

   UIGraphicsBeginImageContext( imgSize );
   [img drawInRect:CGRectMake(0,0,expectedLabelSize.width,expectedLabelSize.height)];
   UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   cell.sampleTitleLabel.backgroundColor = [UIColor colorWithPatternImage:newImage];
   return cell;
}

我已经看到IOS7的一些更新版本但尚未尝试。 希望这段代码能帮助别人!

1 个答案:

答案 0 :(得分:0)

我认为问题在于你采用标签大小的方式,在iOS 7中不推荐使用方法sizeWithFont: constrainedToSize: lineBreakMode:,尝试使用此代码:

...
CGSize maximumLabelSize = CGSizeMake(319,9999);
CGRect labrect = [cell.sampleTitleLabel.text boundingRectWithSize:maximumLabelSize 
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                             attributes:@{NSFontAttributeName:cell.recipeTitleLabel.font} 
                                             context:Nil];
UIGraphicsBeginImageContext( imgSize );
[img drawInRect:CGRectMake(0,0,labrect.size.width,labrect.size.height)];

...