NSButton的自定義操作-Swift

由于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))
        }
    }
    
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容