NSButton Toggle:在OSX 10.11上删除了OnClick标题

时间:2016-12-30 08:48:50

标签: cocoa osx-elcapitan nsbutton xcode8.1

我在XIB中使用切换按钮

AwakeFromNib 中的

:我设置按钮的标题和BG图像。 代码在 OSX 10.10.5及更低版本之前非常有效,但在更高版本时,当我点击按钮时文本被删除

设置属性标题

    [self.deleteButton setWantsLayer:YES];
    self.deleteButton.layer.backgroundColor = [self setButtonBGColor];
    [self setButtonTitleFor:self.deleteButton
                   toString:@"Delete"];
    [self.deleteButton setLayerContentsRedrawPolicy:NSViewLayerContentsRedrawOnSetNeedsDisplay];



- (void)setButtonTitleFor:(NSButton*)button toString:(NSString*)title
{
    NSAttributedString *attrString = [self getAttributedStringForString:title];
    [button setAttributedTitle:attrString];
}

enter image description here enter image description here

应该做任何想法。

enter image description here

1 个答案:

答案 0 :(得分:0)

所以最后做对了

NSButtonCell的子类化帮助了我

<强> RPButtonTextTopCell.h

@interface RPButtonTextTopCell:NSButtonCell

@end

<强> RPButtonTextTopCell.m

@implementation RPButtonTextTopCell

-(id) init
{
    self = [super init];
    if (self) {
    }
    return self;
}

-(id) initWithCoder:(NSCoder *)decoder
{
    return [super initWithCoder:decoder];
}

-(id) initTextCell:(NSString *)string
{
    return [super initTextCell:string];
}

-(NSRect)titleRectForBounds:(NSRect)theRect
{
    NSRect titleFrame = [super titleRectForBounds:theRect];
    NSSize titleSize = [[self attributedStringValue] size];

    titleFrame.origin.y = (theRect.origin.y - (theRect.size.height-titleSize.height)*0.5) + 5;

    return titleFrame;
}

@end

使用此自定义类

RPButtonTextTopCell *deleteCell = [[RPButtonTextTopCell alloc] init];
deleteCell.backgroundColor      = [self setNSButtonBGColor];

[self.deleteButton setCell:deleteCell];
[self setButtonTitleFor:self.deleteButton
               toString:@"Delete"];
[self.deleteButton setAction:@selector(deleteButtonClicked:)];
[self.deleteButton setTarget:self];

并解决了......