Mac開發基礎11-NSTextField(一)
NSTextField 是 macOS 應用中常用的 UI 元素之一,它用于顯示和輸入文本。NSTextField 提供了豐富的 API 來定制和處理用戶輸入。
常見 API 和技巧
1. 初始化 NSTextField
程序化創建
Objective-C
NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 22)];
[textField setStringValue:@"Initial Text"];
Swift
let textField = NSTextField(frame: NSMakeRect(0, 0, 200, 22))
textField.stringValue = "Initial Text"
Interface Builder(IB)創建
在 IB 中拖動一個 NSTextField 到界面。然后在代碼中通過 IBOutlet 連接。
Objective-C
@property (weak) IBOutlet NSTextField *textField;
Swift
@IBOutlet weak var textField: NSTextField!
2. 設置和獲取文本值
設置文本
Objective-C
[self.textField setStringValue:@"New Text"];
Swift
self.textField.stringValue = "New Text"
獲取文本
Objective-C
NSString *currentText = [self.textField stringValue];
Swift
let currentText = self.textField.stringValue
3. 占位符文字
占位符文字提供了提示信息,當文本框為空時顯示。
設置占位符文字
Objective-C
[self.textField setPlaceholderString:@"Enter your text here"];
Swift
self.textField.placeholderString = "Enter your text here"
4. 文本對齊和樣式
設置文本對齊
Objective-C
[self.textField setAlignment:NSTextAlignmentCenter];
Swift
self.textField.alignment = .center
設置文本顏色和字體
Objective-C
[self.textField setTextColor:[NSColor redColor]];
[self.textField setFont:[NSFont fontWithName:@"Helvetica" size:14]];
Swift
self.textField.textColor = NSColor.red
self.textField.font = NSFont(name: "Helvetica", size: 14)
5. 禁用編輯和選擇
有時你可能希望文本框只用于顯示,而不是讓用戶編輯。
禁用編輯
Objective-C
[self.textField setEditable:NO];
Swift
self.textField.isEditable = false
禁用選擇
Objective-C
[self.textField setSelectable:NO];
Swift
self.textField.isSelectable = false
6. 處理用戶輸入
通過委托處理輸入(NSTextFieldDelegate)
通過實現 NSTextFieldDelegate 的方法,可以處理用戶輸入時的各種事件。
Objective-C
@interface ViewController : NSViewController <NSTextFieldDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textField.delegate = self;
}
- (void)controlTextDidChange:(NSNotification *)notification {
NSTextField *textField = notification.object;
NSLog(@"New value: %@", textField.stringValue);
}
@end
Swift
class ViewController: NSViewController, NSTextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
func controlTextDidChange(_ obj: Notification) {
if let textField = obj.object as? NSTextField {
print("New value: \(textField.stringValue)")
}
}
}
7. 回車鍵處理(自動完成)
可以捕捉回車鍵事件并處理它,例如自動完成輸入。
回車鍵處理
Objective-C
- (void)controlTextDidEndEditing:(NSNotification *)obj {
NSNumber *movement = obj.userInfo[@"NSTextMovement"];
if (movement.integerValue == NSReturnTextMovement) {
NSLog(@"Return key pressed");
}
}
Swift
func controlTextDidEndEditing(_ obj: Notification) {
if let movement = (obj.userInfo?["NSTextMovement"] as? NSNumber)?.intValue,
movement == NSReturnTextMovement {
print("Return key pressed")
}
}
8. 自定義背景和邊框
可以通過屬性定制 NSTextField 的外觀。
自定義背景顏色和邊框顏色
Objective-C
[self.textField setDrawsBackground:YES];
[self.textField setBackgroundColor:[NSColor yellowColor]];
[self.textField setBordered:YES];
[self.textField setBezeled:YES];
[self.textField setBezelStyle:NSTextFieldRoundedBezel];
Swift
self.textField.drawsBackground = true
self.textField.backgroundColor = .yellow
self.textField.isBordered = true
self.textField.isBezeled = true
self.textField.bezelStyle = .roundedBezel
9. 格式化輸入
通過配置 NSFormatter,可以限制并格式化用戶輸入。
使用 NSNumberFormatter 格式化數值輸入
Objective-C
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
[self.textField setFormatter:formatter];
Swift
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
self.textField.formatter = formatter
10. 失去焦點/達到焦點事件處理
可以捕捉文本框的焦點事件,以處理特定的需求。
處理焦點事件
Objective-C
- (BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor {
NSLog(@"Text field gained focus");
return YES;
}
- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor {
NSLog(@"Text field lost focus");
return YES;
}
Swift
func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
print("Text field gained focus")
return true
}
func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
print("Text field lost focus")
return true
}
深入探討 NSTextField
1. 響應鏈機制
NSTextField 是響應鏈的一部分,當用戶在文本框中進行操作時,事件會沿著響應鏈傳遞,直到找到可以處理該事件的對象。借助響應鏈機制,NSTextField 可以委托事件處理給其委托對象,比如 controlTextDidChange:
2. KVO 和 KVC
NSTextField 可以使用鍵值觀察(KVO)來觀察其屬性變化。比如觀察 stringValue 屬性的變化:
KVO 觀察示例
Objective-C
[self.textField addObserver:self forKeyPath:@"stringValue" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"stringValue"]) {
NSLog(@"New value: %@", change[NSKeyValueChangeNewKey]);
}
}
- (void)dealloc {
[self.textField removeObserver:self forKeyPath:@"stringValue"];
}
Swift
textField.addObserver(self, forKeyPath: "stringValue", options: .new, context: nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "stringValue" {
print("New value: \(change?[.newKey] ?? "")")
}
}
deinit {
textField.removeObserver(self, forKeyPath: "stringValue")
}
3. 關聯屬性和用戶屬性
可以為 NSTextField 添加額外的元數據:
Objective-C
objc_setAssociatedObject(self.textField, @"key", @"value", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
NSString *value = objc_getAssociatedObject(self.textField, @"key");
NSLog(@"Associated Value: %@", value);
Swift
objc_setAssociatedObject(textField, "key" as NSString, "value", .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let value = objc_getAssociatedObject(textField, "key" as NSString) as? String
print("Associated Value: \(String(describing: value))")
4. 利用 Core Text 實現高級文本處理
NSTextField 可以與 Core Text 協作,實現更復雜的文本格式化和繪制。
繪制富文本
Objective-C
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Hello, World!"
attributes:@{NSForegroundColorAttributeName: [NSColor blueColor],
NSFontAttributeName: [NSFont fontWithName:@"Helvetica-Bold" size:16]}];
[textField setAttributedStringValue:attrString];
Swift
let attrString = NSAttributedString(string: "Hello, World!", attributes: [.foregroundColor: NSColor.blue, .font: NSFont(name: "Helvetica-Bold", size: 16)!])
textField.attributedStringValue = attrString
5. 支持動態 Type 和 Accessibility
NSTextField 支持響應 macOS 的動態類型設置和輔助功能(Accessibility),可以為每個用戶提供更佳的使用體驗。
啟用輔助功能
默認情況下,NSTextField 就支持輔助功能。如果有特定需求,可以通過 NSAccessibility 協議進一步自定義:
Objective-C
// Implement NSAccessibility protocol methods
- (NSArray *)accessibilityActionNames {
return @[NSAccessibilityPressAction];
}
- (void)accessibilityPerformPress {
NSLog(@"Accessibility action performed");
}
Swift
// Implement NSAccessibility protocol methods
override func accessibilityActionNames() -> [NSAccessibility.ActionName] {
return [.press]
}
override func accessibilityPerformAction(_ action: NSAccessibility.ActionName) {
if action == .press {
print("Accessibility action performed")
}
}
將來的你會感謝今天如此努力的你!
版權聲明:本文為博主原創文章,未經博主允許不得轉載。

浙公網安備 33010602011771號