NSView의 배경색을 변경하는 가장 좋은 방법
저는 지금 가장 좋은 방법을 찾고 있습니다.backgroundColor
의NSView
또한 적절한 설정을 할 수 있으면 좋겠습니다.alpha
을 위해 가면을 쓰다NSView
. 예를 들면:
myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f
green:0.251f
blue:0.337
alpha:0.8];
눈치채다NSWindow
이 방법을 가지고 있습니다.저는 이 방법을 별로 좋아하지 않습니다.NSColorWheel
, 또는NSImage
background options(백그라운드 옵션)를 선택할 수 있습니다.그러나, 최선이 되는 경우는, 기꺼이 사용합니다
그래, 네 대답이 맞았어.코코아 방법을 사용할 수도 있습니다.
- (void)drawRect:(NSRect)dirtyRect {
// set any NSColor for filling, say white:
[[NSColor whiteColor] setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
Swift의 경우:
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// #1d161d
NSColor(red: 0x1d/255, green: 0x16/255, blue: 0x1d/255, alpha: 1).setFill()
dirtyRect.fill()
}
}
쉽고 효율적인 솔루션은 핵심 애니메이션 계층을 백업 저장소로 사용하도록 보기를 구성하는 것입니다.그럼, 을 사용할 수 있습니다.-[CALayer setBackgroundColor:]
레이어의 배경색을 설정합니다.
- (void)awakeFromNib {
self.wantsLayer = YES; // NSView will create a CALayer automatically
}
- (BOOL)wantsUpdateLayer {
return YES; // Tells NSView to call `updateLayer` instead of `drawRect:`
}
- (void)updateLayer {
self.layer.backgroundColor = [NSColor colorWithCalibratedRed:0.227f
green:0.251f
blue:0.337
alpha:0.8].CGColor;
}
다 됐다! 더 이상 어쩔 수 없다!
스토리보드 애호가라면 코드 라인이 필요 없는 방법이 있습니다.
NSView에 서브뷰로 추가하고 NSBox의 프레임을 NSView와 동일하게 조정합니다.
스토리보드 또는 XIB에서 제목 위치를 없음으로, 상자 유형을 사용자 정의로, 테두리 유형을 "없음"으로, 테두리 색상을 원하는 대로 변경합니다.
다음은 스크린샷입니다.
결과는 다음과 같습니다.
먼저 WantsLayer를 YES로 설정하면 레이어 배경을 직접 조작할 수 있습니다.
[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];
내가 방법을 알아낸 것 같아
- (void)drawRect:(NSRect)dirtyRect {
// Fill in background Color
CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}
편집/갱신: Xcode 8.3.1 • Swift 3.1
extension NSView {
var backgroundColor: NSColor? {
get {
guard let color = layer?.backgroundColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.backgroundColor = newValue?.cgColor
}
}
}
사용방법:
let myView = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
print(myView.backgroundColor ?? "none") // NSView's background hasn't been set yet = nil
myView.backgroundColor = .red // set NSView's background color to red color
print(myView.backgroundColor ?? "none")
view.addSubview(myView)
나는 이 모든 답을 검토했지만 불행히도 나에게 맞는 답은 하나도 없었다.그러나 약 1시간 동안 검색한 결과, 매우 간단한 방법을 발견했습니다. : )
myView.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.9);
최적의 솔루션:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.wantsLayer = YES;
}
return self;
}
- (void)awakeFromNib
{
float r = (rand() % 255) / 255.0f;
float g = (rand() % 255) / 255.0f;
float b = (rand() % 255) / 255.0f;
if(self.layer)
{
CGColorRef color = CGColorCreateGenericRGB(r, g, b, 1.0f);
self.layer.backgroundColor = color;
CGColorRelease(color);
}
}
Swift의 경우:
override func drawRect(dirtyRect: NSRect) {
NSColor.greenColor().setFill()
NSRectFill(dirtyRect)
super.drawRect(dirtyRect)
}
NSView의 하위 클래스인 NSBox를 사용하여 쉽게 스타일링할 수 있습니다.
스위프트 3
let box = NSBox()
box.boxType = .custom
box.fillColor = NSColor.red
box.cornerRadius = 5
의심할 여지 없이 가장 쉬운 방법이며 컬러 세트 자산과도 호환됩니다.
신속:
view.setValue(NSColor.white, forKey: "backgroundColor")
목표-C:
[view setValue: NSColor.whiteColor forKey: "backgroundColor"];
인터페이스 빌더:
사용자 정의 속성 추가backgroundColor
인터페이스 빌더, 타입NSColor
.
뷰 레이어를 백업한 후 레이어에 설정하기만 하면 됩니다.
view.wantsLayer = true
view.layer?.backgroundColor = CGColor.white
다음의 테스트를 실시했습니다(Swift에서는 동작했습니다).
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.5).CGColor
Swift 3 에서는, 다음과 같이 확장을 작성할 수 있습니다.
extension NSView {
func setBackgroundColor(_ color: NSColor) {
wantsLayer = true
layer?.backgroundColor = color.cgColor
}
}
// how to use
btn.setBackgroundColor(NSColor.gray)
NSView를 신속하게 서브클래스로 분류하여 이 작업을 수행할 수 있습니다.
class MyView:NSView {
required init?(coder: NSCoder) {
super.init(coder: coder);
self.wantsLayer = true;
self.layer?.backgroundColor = NSColor.redColor().CGColor;
}
}
이것에 의해, 애플리케이션 실행중의 시스템 전체의 외관 변경(어두운 모드 온/오프)이 서포트됩니다.뷰 클래스를 먼저 BackgroundColorView로 설정하면 Interface Builder에서 배경색을 설정할 수도 있습니다.
class BackgroundColorView: NSView {
@IBInspectable var backgroundColor: NSColor? {
didSet { needsDisplay = true }
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
wantsLayer = true
}
override var wantsUpdateLayer: Bool { return true }
override func updateLayer() {
layer?.backgroundColor = backgroundColor?.cgColor
}
}
RMSkinned View를 확인합니다.NSView의 배경색은 Interface Builder 내에서 설정할 수 있습니다.
재사용 가능한 소규모 클래스(Swift 4.1)
class View: NSView {
var backgroundColor: NSColor?
convenience init() {
self.init(frame: NSRect())
}
override func draw(_ dirtyRect: NSRect) {
if let backgroundColor = backgroundColor {
backgroundColor.setFill()
dirtyRect.fill()
} else {
super.draw(dirtyRect)
}
}
}
// Usage
let view = View()
view.backgroundColor = .white
언급URL : https://stackoverflow.com/questions/2962790/best-way-to-change-the-background-color-for-an-nsview
'programing' 카테고리의 다른 글
VBA에서 다음 줄의 코드를 계속하는 방법 (0) | 2023.04.11 |
---|---|
WPF 타이머 컨트롤은 어디에 있습니까? (0) | 2023.04.11 |
bash 스텝n을 사용하여 범위를 작성하려면 어떻게 해야 합니까?(증분으로 일련의 숫자를 생성합니다.) (0) | 2023.04.11 |
Git 푸시 오류: 리포지토리를 찾을 수 없습니다. (0) | 2023.04.11 |
Windows에서 cURL을 설치하고 사용하는 방법 (0) | 2023.04.11 |