我想在NSTabViewItem
添加一个带有一些文字的图标。
请帮助我使用drawLabel:inRect:
方法中的代码。
- (id)initWithCoder:(NSCoder *)decoder
{
[super initWithCoder:decoder];
tabCell = [[NSBrowserCell alloc] initImageCell:[NSImage
imageNamed:@"xyz"]];
[tabCell setLeaf:YES];
[tabCell setFont:[[self tabView] font]];
[tabCell setStringValue: [self label]];
return self;
}
- (void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)tabRect
{
{ // modify the rect a tad so the cell draws properly..
tabRect.origin.y += 2;
tabRect.size.width += 16;
}
[tabCell drawWithFrame:tabRect inView:[self tabView]];
}
- (NSSize)sizeOfLabel:(BOOL)shouldTruncateLabel
{
NSSize superSize = [super sizeOfLabel:shouldTruncateLabel];
NSImage *icon = [tabCell image];
superSize.width += [icon size].width-4;
return superSize;
}
我可以在NSTabViewItem
添加一个图标,但由于图标很大,所以图标会从标签中显示出来。如何将图标大小保持在TabViewItem
?
答案 0 :(得分:1)
不确定,如果您的问题得到解决,我有类似的用例,我正在使用drawLabel并附加图片,
参考代码段,
- (void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)tabRect{
NSImage *pImage = [self getImage];
[[NSGraphicsContext currentContext] saveGraphicsState];
NSAffineTransform* xform = [NSAffineTransform transform];
[xform translateXBy:0.0 yBy: tabRect.size.height];
[xform scaleXBy:1.0 yBy:-1.0];
[xform concat];
if(pImage){
[pImage drawInRect:NSMakeRect(tabRect.origin.x-8,-6,16, 16)fromRect:NSZeroRect
operation:NSCompositeSourceOver
fraction:opacity];
}
[[NSGraphicsContext currentContext] restoreGraphicsState];
[super drawLabel:shouldTruncateLabel inRect:tabRect];
NSLog(@" Inside drawRect text (%@)",[self labeltitle]);
}
答案 1 :(得分:0)
此代码对我有用(快速3):
{{1}}
未经充分测试,如果iconWidth更改,您可能必须更改某些常量。
答案 2 :(得分:0)
基于Amitg2k12的示例并添加了一些内容:
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (self) {
[self setToolTip:[self label]];
[self setLabel:@" "];
}
return self;
}
- (NSSize)sizeOfLabel:(BOOL)computeMin {
return NSMakeSize(16, 18);
}
- (void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)tabRect {
NSImage *image = [self image];
NSRect destRect = NSMakeRect(tabRect.origin.x, tabRect.origin.y + 2, 16, 16);
[[NSGraphicsContext currentContext] saveGraphicsState];
NSAffineTransform *affineTransform = [NSAffineTransform transform];
[affineTransform translateXBy:NSMaxX(destRect) yBy:NSMinY(destRect)];
[affineTransform scaleXBy:1.0 yBy:-1.0];
[affineTransform concat];
if(image) {
[image drawInRect:NSMakeRect(-NSWidth(destRect), -NSHeight(destRect), 16, 16) fromRect:NSZeroRect
operation:NSCompositeSourceOver
fraction:1.0f];
}
[[NSGraphicsContext currentContext] restoreGraphicsState];
[super drawLabel:shouldTruncateLabel inRect:tabRect];
}
@end