2013-12-17 99 views
0

我一直在網上搜索幾天,但找不到任何解決方案。UILabel背景圖像與UICollectionViewCell相同寬度的標籤尺寸

最後弄清楚如何做到:

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

    NSString *[email protected]"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更新版本,但還沒試呢。 希望這段代碼能幫助別人!

回答

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)]; 

...