由于NSButton不能像UIButton那樣自定義背景色和高亮狀態(tài)下的背景色等,所以需要自定義一個(gè)繼承自NSButton的類,代碼如下:
//
// CustomButton.swift
// MacAppSimple
//
// Created by zhoucz on 2020/11/24.
//
import Foundation
import Cocoa
class CustomButton: NSButton {
fileprivate var _backgroundColor:NSColor = .white
/// 背景色
public var backgroundColor:NSColor{
get{ _backgroundColor }
set{
_backgroundColor = newValue
}
}
fileprivate var _highlightColor:NSColor = .lightGray
/// 高亮背景色
public var highlightColor:NSColor{
get{ _highlightColor }
set{ _highlightColor = newValue }
}
fileprivate var _titleColor:NSColor = .black
/// titile色
public var titleColor:NSColor{
get{ _titleColor }
set{ _titleColor = newValue }
}
fileprivate var _highlightTitleColor:NSColor = .white
/// 高亮狀態(tài)下的title顏色
public var highlightTitleColor:NSColor{
get{ _highlightTitleColor }
set{ _highlightTitleColor = newValue }
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
/// 設(shè)置背景色
if self.isHighlighted {
_highlightColor.set()
}else{
_backgroundColor.set()
}
dirtyRect.fill()
/// 圓角
self.layer?.masksToBounds = true
self.layer?.cornerRadius = dirtyRect.height*0.5
/// 繪制title
if !self.title.isEmpty {
let paraStyle:NSMutableParagraphStyle = NSMutableParagraphStyle()
paraStyle.setParagraphStyle(NSParagraphStyle.default)
paraStyle.alignment = .center
var attr:[NSAttributedString.Key:Any] = [:]
attr[NSAttributedString.Key.font] = NSFont.init(name: "Verdana", size: 14)
attr[NSAttributedString.Key.foregroundColor] = isHighlighted ? highlightTitleColor:titleColor
attr[NSAttributedString.Key.paragraphStyle] = paraStyle
/// 在這里調(diào)整title的位置
let btnString = NSAttributedString(string: self.title,attributes: attr)
btnString.draw(in: NSMakeRect(0, (self.frame.size.height / 2)-10, self.frame.size.width, self.frame.size.height))
}
}
}