Mac開發基礎17-NSButton(二)
NSButton是一個功能強大且靈活多樣的控件,除了基本使用和常見API外,還有一些進階用法和技巧可以提高按鈕的可用性和實現細節。在以下內容中,我會詳細介紹一些進階使用技巧,并封裝一個常用的工具類來實現自定義的多種按鈕類型。
進階使用和技巧
1. 自定義按鈕的外觀和行為
Objective-C
// 自定義按鈕的邊框顏色和寬度
- (void)customizeButtonAppearance:(NSButton *)button {
button.wantsLayer = YES; // 啟用 Core Animation
button.layer.borderColor = [NSColor redColor].CGColor; // 設置邊框顏色
button.layer.borderWidth = 2.0; // 設置邊框寬度
button.layer.cornerRadius = 5.0; // 設置圓角半徑
button.layer.masksToBounds = YES; // 避免超出的部分顯示
}
Swift
// 自定義按鈕的邊框顏色和寬度
func customizeButtonAppearance(_ button: NSButton) {
button.wantsLayer = true // 啟用 Core Animation
if let layer = button.layer {
layer.borderColor = NSColor.red.cgColor // 設置邊框顏色
layer.borderWidth = 2.0 // 設置邊框寬度
layer.cornerRadius = 5.0 // 設置圓角半徑
layer.masksToBounds = true // 避免超出的部分顯示
}
}
2. 控制按鈕的按下和松開行為
Objective-C
- (void)addCustomTrackingToButton:(NSButton *)button {
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:button.bounds
options:(NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow)
owner:self
userInfo:nil];
[button addTrackingArea:trackingArea]; // 添加追蹤區域,用于鼠標進入和離開時的事件處理
}
- (void)mouseEntered:(NSEvent *)event {
[self.button setTitle:@"Mouse Entered"]; // 鼠標進入時改變按鈕標題
}
- (void)mouseExited:(NSEvent *)event {
[self.button setTitle:@"Mouse Exited"]; // 鼠標離開時恢復按鈕標題
}
Swift
func addCustomTrackingToButton(_ button: NSButton) {
let trackingArea = NSTrackingArea(rect: button.bounds,
options: [.mouseEnteredAndExited, .activeInKeyWindow],
owner: self,
userInfo: nil)
button.addTrackingArea(trackingArea) // 添加追蹤區域,用于鼠標進入和離開時的事件處理
}
override func mouseEntered(with event: NSEvent) {
self.button.title = "Mouse Entered" // 鼠標進入時改變按鈕標題
}
override func mouseExited(with event: NSEvent) {
self.button.title = "Mouse Exited" // 鼠標離開時恢復按鈕標題
}
3. 自定義按鈕圖層屬性
Objective-C
- (void)setButtonShadow:(NSButton *)button {
button.wantsLayer = YES; // 啟用 Core Animation
button.layer.shadowColor = [NSColor blackColor].CGColor; // 設置陰影顏色
button.layer.shadowOpacity = 0.5; // 設置陰影透明度
button.layer.shadowOffset = CGSizeMake(3, -3); // 設置陰影偏移
button.layer.shadowRadius = 10.0; // 設置陰影半徑
}
Swift
func setButtonShadow(_ button: NSButton) {
button.wantsLayer = true // 啟用 Core Animation
if let layer = button.layer {
layer.shadowColor = NSColor.black.cgColor // 設置陰影顏色
layer.shadowOpacity = 0.5 // 設置陰影透明度
layer.shadowOffset = CGSize(width: 3, height: -3) // 設置陰影偏移
layer.shadowRadius = 10.0 // 設置陰影半徑
}
}
4. 響應鼠標拖動事件
Objective-C
- (void)trackMouseDragForButton:(NSButton *)button {
[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDragged handler:^NSEvent * _Nullable(NSEvent * _Nonnull event) {
NSPoint location = [event locationInWindow];
[NSCursor.closedHandCursor push]; // 鼠標拖動時改變光標為閉手
button.frame = NSMakeRect(location.x - button.frame.size.width / 2,
location.y - button.frame.size.height / 2,
button.frame.size.width,
button.frame.size.height); // 更新按鈕位置
return event;
}];
}
Swift
func trackMouseDragForButton(_ button: NSButton) {
NSEvent.addLocalMonitorForEvents(matching: .leftMouseDragged) { event in
let location = event.locationInWindow
NSCursor.closedHand.push() // 鼠標拖動時改變光標為閉手
button.frame = NSRect(x: location.x - button.frame.size.width / 2,
y: location.y - button.frame.size.height / 2,
width: button.frame.size.width,
height: button.frame.size.height) // 更新按鈕位置
return event
}
}
5. 動畫效果
Objective-C
- (void)animateButton:(NSButton *)button {
// 創建一個基本動畫來改變按鈕的透明度
CABasicAnimation *fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnimation.duration = 1.0; // 動畫持續時間
fadeAnimation.fromValue = @(1.0); // 起始狀態
fadeAnimation.toValue = @(0.0); // 結束狀態
fadeAnimation.autoreverses = YES; // 動畫結束后反轉
fadeAnimation.repeatCount = HUGE_VALF; // 無限循環動畫
// 將動畫添加到按鈕的圖層上
[button.layer addAnimation:fadeAnimation forKey:@"fadeAnimation"];
}
Swift
func animateButton(_ button: NSButton) {
// 創建一個基本動畫來改變按鈕的透明度
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.duration = 1.0 // 動畫持續時間
fadeAnimation.fromValue = 1.0 // 起始狀態
fadeAnimation.toValue = 0.0 // 結束狀態
fadeAnimation.autoreverses = true // 動畫結束后反轉
fadeAnimation.repeatCount = .greatestFiniteMagnitude // 無限循環動畫
// 將動畫添加到按鈕的圖層上
button.layer?.add(fadeAnimation, forKey: "fadeAnimation")
}
封裝工具類
為了方便創建和管理多種類型的按鈕,我們可以封裝一個工具類。這個工具類可以用于生成不同類型的按鈕,并應用各種自定義設置。
Objective-C
#import <Cocoa/Cocoa.h>
@interface NSButtonFactory : NSObject
+ (NSButton *)createCustomButtonWithTitle:(NSString *)title target:(id)target action:(SEL)action;
+ (NSButton *)createImageButtonWithImage:(NSImage *)image target:(id)target action:(SEL)action;
@end
@implementation NSButtonFactory
+ (NSButton *)createCustomButtonWithTitle:(NSString *)title target:(id)target action:(SEL)action {
NSButton *button = [[NSButton alloc] init]; // 初始化按鈕
[button setTitle:title]; // 設置標題
[button setTarget:target]; // 設置目標
[button setAction:action]; // 設置動作方法
[self applyCustomStyleToButton:button]; // 應用自定義樣式
return button;
}
+ (NSButton *)createImageButtonWithImage:(NSImage *)image target:(id)target action:(SEL)action {
NSButton *button = [[NSButton alloc] init]; // 初始化按鈕
[button setImage:image]; // 設置按鈕圖片
[button setTarget:target]; // 設置目標
[button setAction:action]; // 設置動作方法
[self applyCustomStyleToButton:button]; // 應用自定義樣式
return button;
}
+ (void)applyCustomStyleToButton:(NSButton *)button {
button.wantsLayer = YES; // 啟用 Core Animation
button.layer.borderColor = [NSColor blueColor].CGColor; // 設置邊框顏色
button.layer.borderWidth = 1.0; // 設置邊框寬度
button.layer.cornerRadius = 4.0; // 設置圓角半徑
button.layer.masksToBounds = YES; // 避免超出的部分顯示
}
@end
Swift
import Cocoa
class NSButtonFactory {
static func createCustomButton(title: String, target: AnyObject?, action: Selector?) -> NSButton {
let button = NSButton() // 初始化按鈕
button.title = title // 設置標題
button.target = target // 設置目標
button.action = action // 設置動作方法
applyCustomStyle(to: button) // 應用自定義樣式
return button
}
static func createImageButton(image: NSImage, target: AnyObject?, action: Selector?) -> NSButton {
let button = NSButton() // 初始化按鈕
button.image = image // 設置按鈕圖片
button.target = target // 設置目標
button.action = action // 設置動作方法
applyCustomStyle(to: button) // 應用自定義樣式
return button
}
private static func applyCustomStyle(to button: NSButton) {
button.wantsLayer = true // 啟用 Core Animation
button.layer?.borderColor = NSColor.blue.cgColor // 設置邊框顏色
button.layer?.borderWidth = 1.0 // 設置邊框寬度
button.layer?.cornerRadius = 4.0 // 設置圓角半徑
button.layer?.masksToBounds = true // 避免超出的部分顯示
}
}
使用示例
Objective-C
// 創建自定義標題按鈕
NSButton *customButton = [NSButtonFactory createCustomButtonWithTitle:@"Custom Button" target:self action:@selector(buttonClicked:)];
// 創建圖片按鈕
NSButton *imageButton = [NSButtonFactory createImageButtonWithImage:[NSImage imageNamed:@"buttonImage"] target:self action:@selector(buttonClicked:)];
Swift
// 創建自定義標題按鈕
let customButton = NSButtonFactory.createCustomButton(title: "Custom Button", target: self, action: #selector(buttonClicked(_:)))
// 創建圖片按鈕
let imageButton = NSButtonFactory.createImageButton(image: NSImage(named: "buttonImage")!, target: self, action: #selector(buttonClicked(_:)))
將來的你會感謝今天如此努力的你!
版權聲明:本文為博主原創文章,未經博主允許不得轉載。

浙公網安備 33010602011771號