2011-02-02 79 views
4

我想我的IKImageBrowserView通过包装它们并以多行显示它们来显示长标题,但是我一直无法实现。IKImageBrowserView可以显示多行标题吗?

我试过改变在ImageBrowserCell子类中返回的titleFrame的大小,并在标题上设置段落样式以便它应该包裹(NSLineBreakByWordWrapping),但我只能得到一行文本。

有没有人试过吗?我可能会尝试其他建议吗?

回答

6

不容易,我很害怕。一种方法是将imageTitle留空并在CALayer上绘制文字。我能够让它具有相当不错的结果工作:

enter image description here

首先第一件事情 - 因为你不打算使用标准imageTitle属性,你想创造一个新的标题属性您<IKImageBrowserItem> - 符合数据对象。我简单地给我打电话title

然后,您要创建IKImageBrowserCell子类。请务必告诉您的IKImageBrowserView您正在使用自定义单元格;我只写了一个快速类别是:

@implementation IKImageBrowserView(CustomCell) 
- (IKImageBrowserCell *)newCellForRepresentedItem:(id)cell 
{ 
    return [[MyCustomImageBrowserCell alloc] init]; 
} 
@end 

接下来,在你的自定义单元格,覆盖的方法- (CALayer *)layerForType:(NSString *)type。创建和特定层位置类型返回的CALayer:

- (CALayer *)layerForType:(NSString *)type 
{  
    if([type isEqualToString:IKImageBrowserCellBackgroundLayer]) 
    {  
     CALayer *layer = [CALayer layer]; 
     layer.delegate = self; 
     layer.frame = self.frame; // the cell's frame 
     layer.name = type; // a way to refer to the layer location type during drawing if need be 
     [layer setNeedsDisplay]; 
     return layer; 
    } 

    return [super layerForType:type]; 
} 

然后,实现您的自定义单元格的-drawLayer:inContext:方法来处理层的图纸:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context 
{ 
    // Set the current context. 
    [NSGraphicsContext saveGraphicsState]; 
    NSGraphicsContext *nscg = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]; 
    [NSGraphicsContext setCurrentContext:nscg]; 

    NSString *title = [self.representedItem title]; 

    // Wrap and center the text 
    NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; 
    [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; 
    [paragraphStyle setAlignment:NSCenterTextAlignment]; 

    NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; 
    [attrs setObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; 
    [attrs setObject:[NSFont systemFontOfSize:12.0f] forKey:NSFontAttributeName]; 

    CGFloat padding = 4.0f; 

    [title drawInRect:NSMakeRect(
     0, 
     -(self.imageFrame.size.height + padding), 
     self.frame.size.width, 
     100 
    ) withAttributes:attrs]; 

    [NSGraphicsContext restoreGraphicsState]; 
} 

不幸的是,这种方法确实有几个缺点。文字没有得到像imageTitle那样的蓝色选择背景。但是,您可以在IKImageBrowserCellSelectionLayer的自定义CALayer内使用NSBezierPath来绘制自己的选择背景。

希望这足以继续下去。

+0

谢谢你的回复。实际上,我最终使用CATextLayer来实现您的建议。 (我们已经定制了IKImageBrowserCellSelectionLayer在整个框架周围绘制边框来指示选择,所以这里没有问题。) – 2011-08-30 22:19:10

相关问题