带有圆角和背景颜色的NSButton

时间:2016-09-14 11:04:49

标签: swift macos

我想要一个简单的按钮(带圆角的按钮),并为其添加背景。 我尝试了两件事:

1 - 使用圆形按钮图像:这样做很好,直到我需要缩放按钮,这会导致圆形部分看起来很难看。

2 - 扩展按钮并为其添加颜色 - 但是当我点击按钮时我遇到了麻烦 - 我希望“推”状态与“常规”状态颜色相同,但事实并非如此

这是我用来扩展按钮的代码:

 override func drawRect(dirtyRect: NSRect)
    {
        if let bgColor = bgColor {
            self.layer?.cornerRadius = 4
            self.layer?.masksToBounds = true
            self.layer?.backgroundColor = bgColor.CGColor
            bgColor.setFill()

            NSRectFill(dirtyRect)
        }

        super.drawRect(dirtyRect)
    }

无论如何,方法1和方法2都没有用,所以我怎样才能做到这一点? 只是一个简单的按钮.. :(

编辑: 我在问OSX

8 个答案:

答案 0 :(得分:6)

我按了一个按钮然后成功了。它看起来像这样:

代码:

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)
    // Drawing code here.
    if let bgColor = bgColor {
        self.layer?.cornerRadius = 4
        self.layer?.masksToBounds = true
        self.layer?.backgroundColor = bgColor.cgColor
        bgColor.setFill()
        NSRectFill(dirtyRect)
    }
}

drawRect替换为draw,CGColor替换为cgColor。你和我之间的区别在于订单。你最后打电话给super.draw(dirtyRect),我先打电话给它。也许你的按钮看起来像这样:

我希望这可以解决你的问题。

答案 1 :(得分:5)

覆盖NSButtonCell的drawWithFrame方法:

func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) {
    var border = NSBezierPath(roundedRect: NSInsetRect(cellFrame, 0.5, 0.5), xRadius: 3, yRadius: 3)
    NSColor.greenColor().set()
    border.fill()

    var style = NSParagraphStyle.defaultParagraphStyle()
    style.alignment = NSCenterTextAlignment
    var attr = [NSParagraphStyleAttributeName : style, NSForegroundColorAttributeName : NSColor.whiteColor()]

    self.title.drawInRect(cellFrame, withAttributes: attr)
}

答案 2 :(得分:1)

OBJECTIVE-C解决方案(可能会帮助一些人偶然发现这个问题)

这个子类扩展了IB - 所以你可以控制IB:

  • 背景颜色
  • 悬停时的背景颜色
  • 标题颜色
  • 悬停时的标题颜色
  • Corner Radius

它还包括悬停时的小动画。

New controls in IB (click to see screenshot)

//
//  SHFlatButton.h
//
//  Created by SH on 03.12.16.
//  Copyright © 2016 SH. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface SHFlatButton : NSButton

@property (nonatomic, strong) IBInspectable NSColor *BGColor;
@property (nonatomic, strong) IBInspectable NSColor *TextColor;
@property (nonatomic, strong) IBInspectable NSColor *BGColorHover;
@property (nonatomic, strong) IBInspectable NSColor *TextColorHover;
@property (nonatomic) IBInspectable CGFloat CornerRadius;
@property (strong) NSCursor *cursor;

@end

实施......

//
//  SHFlatButton.m
//
//  Created by SH on 03.12.16.
//  Copyright © 2016 SH. All rights reserved.
//

#import "SHFlatButton.h"

@implementation SHFlatButton

- (void)awakeFromNib
{
    if (self.TextColor)
        [self setAttributedTitle:[self textColor:self.TextColor]];

    if (self.CornerRadius)
    {
        [self setWantsLayer:YES];
        self.layer.masksToBounds = TRUE;
        self.layer.cornerRadius = self.CornerRadius;
    }
}


- (void)drawRect:(NSRect)dirtyRect
{
    if (self.BGColor)
    {
        [self.BGColor setFill];
        NSRectFill(dirtyRect);
    }

    [super drawRect:dirtyRect];
}


- (void)resetCursorRects
{
    if (self.cursor) {
        [self addCursorRect:[self bounds] cursor: self.cursor];
    } else {
        [super resetCursorRects];
    }
}


- (void)updateTrackingAreas {

    NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
                                    initWithRect:[self bounds]
                                    options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
                                    owner:self userInfo:nil];
    [self addTrackingArea:trackingArea];
}


- (void)mouseEntered:(NSEvent *)theEvent{
    if ([self isEnabled]) {

        [[self animator]setAlphaValue:0.9];
        if (self.BGColorHover)
            [[self cell] setBackgroundColor:self.BGColorHover];
        if (self.TextColorHover)
            [self setAttributedTitle:[self textColor:self.TextColorHover]];
    }


}

- (void)mouseExited:(NSEvent *)theEvent{
    if ([self isEnabled]) {
        [[self animator]setAlphaValue:1];
        if (self.BGColor)
            [[self cell] setBackgroundColor:self.BGColor];
        if (self.TextColor)
            [self setAttributedTitle:[self textColor:self.TextColor]];
    }
}

- (NSAttributedString*)textColor:(NSColor*)color
{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSCenterTextAlignment];
    NSDictionary *attrsDictionary  = [NSDictionary dictionaryWithObjectsAndKeys:
                                      color, NSForegroundColorAttributeName,
                                      self.font, NSFontAttributeName,
                                      style, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:self.title attributes:attrsDictionary];
    return attrString;
}

编辑:按钮必须禁用边框!

答案 3 :(得分:0)

您需要覆盖功能layoutSubviews,即

override func layoutSubviews() {
        self.layer.cornerRadius = self.frame.height/2
        self.layer.borderColor = UIColor.blue.cgColor
        self.layer.borderWidth = 2
    } 

我已经提交了一个示例项目here。所有相关的代码都是用button.swift编写的,它是在swift 3中。另外,我还没有为按钮设置背景图像,我将这个任务留给你。

P.S。:以下答案适用于UIButton,而不是NSButton。可能其中一些是有效的,可能不是一切......

答案 4 :(得分:0)

只是尝试将这两行代码添加到您的函数中。我认为您在边框宽度方面遇到问题。

覆盖func drawRect(dirtyRect:NSRect)

{
    if let bgColor = bgColor {
        self.layer?.cornerRadius = 4
        self.layer?.masksToBounds = true
        self.layer?.backgroundColor = bgColor.CGColor
        self.layer?.borderColor = UIColor.blackcolor()
        self.layer?.borderWidth = 2.0

        bgColor.setFill()

        NSRectFill(dirtyRect)
    }

    super.drawRect(dirtyRect)
}

答案 5 :(得分:-1)

简单的3行功能。

@IBOutlet weak var button: UIButton!

func setButton(color: UIColor, title: String)  {
    button.backgroundColor = color
    button.setTitle(title, forState: .Normal)
    button.layer.cornerRadius = 8.0
}

并称之为

 setButton(UIColor.redColor(), title: "Hello")

答案 6 :(得分:-1)

enter image description here如果您想要一个圆形按钮,请打开您的main.storyboard,单击按钮并单击“显示身份检查器”。在“用户定义的运行时属性”下,单击“小+”符号两次。然后将代码更改为此类enter image description here

答案 7 :(得分:-1)

以下是对我有用的内容( Swift 4 )。

设置背景颜色:

_conn.Open();
string compare = "SELECT address, COUNT(*) FROM melena_edws m WHERE EXISTS (SELECT address FROM actuals a WHERE m.address = a.address) GROUP BY address ";

CtreeSqlCommand cmd = new CtreeSqlCommand(compare, _conn);
CtreeSqlDataReader reader = cmd.ExecuteReader()
if(reader.HasRows)
{
    while (reader.Read())
    {
        Console.WriteLine(string.Format("{0,12}", reader["address"]));
        Compare($"{reader["address"]} ");
    }
}
else
{
    // Display your message
}

reader.Dispose();
_conn.Close();

设置拐角半径:

 myButton.layer?.backgroundColor = CGColor.customSilver