2016-09-14 10 views
12

간단한 푸시 버튼 (둥근 모서리가있는 버튼)과 배경을 추가하고 싶습니다. 2 가지를 시도했습니다.둥근 모서리와 배경색이있는 NSButton

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에 대해 부탁 해요

+0

버튼을 눌렀을 때 크기 나 색상을 변경 하시겠습니까? 이렇게? - http://www.gifmania.co.uk/Web-Design-Animated-Gifs/Animated-Web-Buttons/Green-Web-Buttons/Green-Rounded-Button-90785.gif – Jordan

+0

NSButton을 가지고 싶습니다. 규칙적인 동작이지만 배경색과 둥근 모서리가 있습니다. – Roee84

답변

4

무시 NSButtonCell의 drawWithFrame 방법 : 즉, 당신은 기능 layoutSubviews를 오버라이드 (override) 할 필요가

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) 
} 
+0

결과는 NSButton override와 동일합니다. drawRect – Roee84

+0

이 코드의 문제점은 무엇입니까? 그것은 나를 위해 작동 – rocky

+0

버튼의 제목을 잃는다 – Roee84

2

,

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

샘플 프로젝트 here을 커밋했습니다. 관련 코드는 모두 button.swift로 작성되었으며 또한 스위프트 3에 있습니다. 또한 단추의 배경 이미지를 설정하지 않았으므로 그 작업을 사용자에게 맡깁니다.

P .: 답변은 NSButton이 아닌 UIButton에 대한 것입니다. 아마도 그 중 일부는 유효 할 것이며 아마 모든 것이 유효하지 않을 것입니다 ...

+0

고마워요,하지만 IOS X에서 NSButton에 대해 물어 보았습니다. – Roee84

0

간단한 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 
} 

하고, 버튼이 반올림하려는 main.storyboard을 열면 같은

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

고마워요.하지만 OS X에서 NSButton에 대해 물어 보았습니다. – Roee84

1

enter image description here과 같이 호출 버튼을 클릭의 클릭은 "신원 관리자를 표시" . "사용자 정의 런타임 속성에서 두 번 작은 + 기호를 클릭하고 코드를 다음과 같이 바꿉니다. enter image description here

+0

고마워요.하지만 iOS에서 UButton이 아니라 OS X에서 NSButton에 대해 물었습니다. – Roee84

+0

OS X에서도 잘 작동합니다. –

+0

버튼의 배경색을 변경하고 싶습니다. – Roee84

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) 
} 
+0

차이를 만들지 않았습니까? – Roee84

4

나는 버튼을 만들어 성공 그것은 다음과 같습니다.

(210)

코드 :

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는 무승부로 대체하고, CGColor은 cgColor로 대체됩니다. 너와 나 사이의 차이점이 순서 야. 마지막으로 super.draw(dirtyRect)에 전화를 걸었습니다.어쩌면 당신의 버튼은 다음과 같습니다

나는이 문제를 해결할 수 있기를 바랍니다.

+0

고마워,하지만 여기 다른 해결책으로는 제목에 문제가있다. – Roee84

+0

그래, 나는 당신이 당신의 코드의 일부를 보여 주었다고 생각하고 코드가 그 제목을 잘 보여줄 수 있다고 생각했다. 이 함수의 마지막에'self.title.draw (...)'를 추가하면 제목이 나타납니다. –

1

목적-C 솔루션

이 sublass (일부 사람들은이 스레드 우연히 도움이 될 것은) IB 확장 - 그래서 당신은 IB 중 하나를 제어 할 수 있습니다

  • 배경 색상
  • 배경 색상을 호버
  • 제목 색상
  • 제목 호버 온 컬러
  • 모서리 반경

호버에는 알파 애니메이션이 포함되어 있습니다.

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; 
} 

편집 : 버튼 MUST은 국경 사용할 수 있습니다!

관련 문제