NSButton的自定义操作-Swift

由于NSButton不能像UIButton那样自定义背景色和高亮状态下的背景色等,所以需要自定义一个继承自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
    /// 高亮状态下的title颜色
    public var highlightTitleColor:NSColor{
        get{ _highlightTitleColor }
        set{ _highlightTitleColor = newValue }
    }

    
    
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        /// 设置背景色
        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
           
             /// 在这里调整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))
        }
    }
    
}

你可能感兴趣的:(NSButton的自定义操作-Swift)