【问题标题】:Creating Round NSButtons for insertion into NSToolbar创建圆形 NSButton 以插入 NSToolbar
【发布时间】:2013-04-11 21:33:13
【问题描述】:

对于个人项目,我目前正在尝试在 Automator for OS X 中复制工具栏的视觉样式。我已经尝试了几乎所有方法来让 NSToolbar 中的 NSButtons 在视觉上看起来相似,但不能似乎找出了微妙的 UI 组件来解决它,所以我转向 Stack Overflow 上的聪明头脑。

我正在尝试做的事情:我正在尝试复制 Automator 工具栏按钮的视觉样式:

设置:目前我有活动按钮状态、非活动按钮状态和按下按钮状态的 tiff 图像。我想使用这些图像作为 NSButtonCell 的背景。现在,我将 NSButtonCell 子类化(代码如下),并在 Interface Builder 的 XIB 文件中将 NSButtonCell 类设置为 TFToolbarButtonCell。在 NSButtonCell 的子类中,我重写了 -drawWithFrame:inView 以在框架中绘制适当的状态图像;我还重写了 -highlight:withFrame:inView 以在单击按钮时绘制按下的图像。

非常感谢我在这里可能做错的任何方向!

TFToolbarButtonCell.h

#import <Cocoa/Cocoa.h>

@interface TFToolbarButtonCell : NSButtonCell

    @property (nonatomic, strong) NSImage *onImage;
    @property (nonatomic, strong) NSImage *offImage;
    @property (nonatomic, strong) NSImage *highlightImage;

@end

TFToolbarButtonCell.m

#import "TFToolbarButtonCell.h"

@implementation TFToolbarButtonCell

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

    - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
    {
        if([self state]){
            [self.onImage drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
        } else {
            [self.offImage drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
        }
    }

   - (void)highlight:(BOOL)flag withFrame:(NSRect)cellFrame inView:(NSView *)controlView
    {
        if(flag){
            [self.highlightImage drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
        }
    }

@end

【问题讨论】:

    标签: objective-c macos uikit appkit


    【解决方案1】:

    我认为你可以通过继承 NSButton 并实现来完成你想要的

    - (void)mouseDown:(NSEvent *)theEvent
    - (void)mouseUp:(NSEvent *)theEvent
    

    以及您自己设置非活动状态的方法。

    这些方法会调用

    - (void)setImage:(NSImage *)anImage
    

    使用不同的图像从活动状态更改为按下状态。

    您还必须在您的 NSButton 上取消选中 Interface Builder 中的“Bordered”以停止显示按钮背景。

    还有,打电话

    - (void)setEnabled:(BOOL)enabled
    

    在 NSToolbarItem 上将调色板标签更改为活动/非活动(灰色按钮下方的文本)。

    【讨论】:

    • 谢谢。只剩下一个问题:在 NSButton 子类的 initWithFrame 中,我将按钮类型设置为 NSMomentaryChangeButton,然后将图像设置为活动状态(我不会担心非活动状态)。但是,当我构建并运行并且工具栏与按钮一起初始化时,除非首先单击,否则不会出现活动图像。关于为什么会发生这种情况的任何想法?
    • 您需要在 - (void) awakeFromNib 中调用它,因为它将在 nib 完成加载后调用。见:stackoverflow.com/questions/6436895/init-and-awakefromnib
    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多