這節主要通過實踐來學習NSTextField的使用,初步了解NSTextField的代理方法、常用屬性、常用樣式等內容,完整代碼可以參看源碼目錄下的NSTextField_Example項目。
TextField Delegate
NSTextFieldDelegate
承繼于NSControlTextEditingDelegate
,實際常用的只有NSControlTextEditingDelegate
,具體內容如下:
func controlTextDidBeginEditing(Notification)
func controlTextDidChange(Notification)
func controlTextDidEndEditing(Notification)
func control(NSControl, isValidObject: Any?) -> Bool
func control(NSControl, didFailToValidatePartialString: String, errorDescription: String?)
func control(NSControl, didFailToFormatString: String, errorDescription: String?) -> Bool
func control(NSControl, textShouldBeginEditing: NSText) -> Bool
func control(NSControl, textShouldEndEditing: NSText) -> Bool
func control(NSControl, textView: NSTextView, completions: [String], forPartialWordRange: NSRange, indexOfSelectedItem: UnsafeMutablePointer<Int>) -> [String]
func control(NSControl, textView: NSTextView, doCommandBy: Selector) -> Bool
以上的代碼方法看起來非常,但在實踐開發中,大數用到的主要是下面三個:
extension ViewController: NSTextFieldDelegate
{
/// 開始編輯
func controlTextDidBeginEditing(_ obj: Notification) {
print("controlTextDidBeginEditing")
}
/// 結束編輯
func controlTextDidEndEditing(_ obj: Notification) {
print("controlTextDidEndEditing")
}
/// 內容改變
func controlTextDidChange(_ obj: Notification) {
let textField = obj.object as? NSTextField
print("controlTextDidChange,text:" + (textField?.stringValue ?? ""))
}
}
TextField 常用屬性
我們可以通過查看NSTextField.h
文件,來獲取到 NSTextField
的常用屬性和方法有以下這些:
// 內容為空時的提示文案
@property (nullable, copy) NSString *placeholderString;
// 內容為空時的提示文案,富文本
@property (nullable, copy) NSAttributedString *placeholderAttributedString;
// 背景色
@property (nullable, copy) NSColor *backgroundColor;
// 是否繪制背景
@property BOOL drawsBackground;
// 文字顏色
@property (nullable, copy) NSColor *textColor;
// 是否繪制邊框
@property (getter=isBordered) BOOL bordered;
// 是否貝塞爾繪制
@property (getter=isBezeled) BOOL bezeled;
// 是否可編輯
@property (getter=isEditable) BOOL editable;
// 是否可選中
@property (getter=isSelectable) BOOL selectable;
// 選擇文本框時調用
- (void)selectText:(nullable id)sender;
// 設置代理
@property (nullable, weak) id<NSTextFieldDelegate> delegate;
// 是否允許開始編輯文本框
- (BOOL)textShouldBeginEditing:(NSText *)textObject;
// 是否允許結束編輯文本框
- (BOOL)textShouldEndEditing:(NSText *)textObject;
// 文本框進入編輯的通知
- (void)textDidBeginEditing:(NSNotification *)notification;
- (void)textDidEndEditing:(NSNotification *)notification;
// 文本框內容發生變化的通知
- (void)textDidChange:(NSNotification *)notification;
// 獲取是否接受第一響應
@property (readonly) BOOL acceptsFirstResponder;
// 設置貝塞爾風格
@property NSTextFieldBezelStyle bezelStyle;
@property CGFloat preferredMaxLayoutWidth;
// 要顯示的最大行數。默認值0表示沒有限制。如果文本達到了允許的行數,或者容器的高度不能容納所需的行數,則文本將被剪切
@property NSInteger maximumNumberOfLines;
TextField文字居中
在前面內容,已經了解TextField
的基本使用,但是發現使用時發現TextField
中的文字沒有居中顯示,現在這我們來實現一個單行、文字居中的TextField
。
在實現單行文字居中的效果前,我們需要先了解NSTextFieldCell
,它的作用是增強Cell的文本顯示功能的對象。
TextFieldCell
的文字默認點貼著頂部邊框的,我們可以在TextFieldCell
渲染的時候,通過調用內容的y
坐標來調整文本的,首頁我選擇自定義一個承繼于NSTextFieldCell
的子類,因為我們希望他是單行可滾動的,所以需要設置isScrollable
為true
:
class CustomTextFieldCell: NSTextFieldCell {
override init(textCell string: String) {
super.init(textCell: string)
self.isScrollable = true
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
接下來我們需要計算文字居中需要距離頂部的偏移量,以獲取文字居中的frame:
extension CustomTextFieldCell {
private func adjustedFrameToVerticallyCenter(frame: NSRect) -> NSRect {
let ascender = font?.ascender ?? 0.0
let descender = font?.descender ?? 0.0
let offset = ceilf(Float(NSHeight(frame)/2 - ascender - descender))
return NSInsetRect(frame, 0, CGFloat(offset))
}
}
獲得修正后的frame后,我在文字繪制的時候調整其frame即可達到小居中的效果:
extension CustomTextFieldCell {
override func edit(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, event: NSEvent?) {
let frame = adjustedFrameToVerticallyCenter(frame: rect)
super.edit(withFrame: frame, in: controlView, editor: textObj, delegate: delegate, event: event)
}
override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
let frame = adjustedFrameToVerticallyCenter(frame: rect)
super.select(withFrame: frame, in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
let frame = adjustedFrameToVerticallyCenter(frame: cellFrame)
super.drawInterior(withFrame: frame, in: controlView)
}
}
我們實現了TextFieldCell
后,在創建TextField
時,把TextField
的cell
指定為我們自定義的TextFieldCell
,即可以實現最終的效果:
lazy var centerTextField: NSTextField = {
let v = NSTextField()
v.frame = NSRect(x: 50, y: 190, width: 100, height: 38)
let cell = CustomTextFieldCell(textCell: "CustomTextFieldCell")
cell.isEditable = true
v.cell = cell
return v
}()
快捷鍵支持
NSTextfield
本身是不會處理系統事件的,如果在文本框中我們需要支持復制、粘貼這類事情,我們則需要單獨去監聽鍵盤事件。我們只需要重寫NSResponder
中的performKeyEquivalent(with:)
:
// 處理按鍵事件
func performKeyEquivalent(with event: NSEvent) -> Bool
重寫該方法以處理按鍵事件。如果事件中的character code或codes與接收方的鍵值匹配,則接收方應響應事件并返回true。如果不重寫,該方法默認返回false,什么也不做。
了解performKeyEquivalent(with:)
的作用后,我們只要重寫該方法并通過按鍵值來做相應的處理,卻可以實現相應的快捷功能:
extension NSTextField {
override open func performKeyEquivalent(with event: NSEvent) -> Bool {
let modifierkeys = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
let key = event.characters ?? ""
/// 點擊 esc 取消焦點
if modifierkeys.rawValue == 0 && key == "\u{1B}" {
self.window?.makeFirstResponder(nil)
}
// command + shift + z 還原
if modifierkeys == [.command, .shift] && key == "z" {
self.window?.firstResponder?.undoManager?.redo()
return true
}
if modifierkeys != .command {
return super.performKeyEquivalent(with: event)
}
switch key {
case "a": // 撤消
return NSApp.sendAction(#selector(NSText.selectAll(_:)), to: self.window?.firstResponder, from: self)
case "c": // 復制
return NSApp.sendAction(#selector(NSText.copy(_:)), to: self.window?.firstResponder, from: self)
case "v": // 粘貼
return NSApp.sendAction(#selector(NSText.paste(_:)), to: self.window?.firstResponder, from: self)
case "x": // 剪切
return NSApp.sendAction(#selector(NSText.cut(_:)), to: self.window?.firstResponder, from: self)
case "z": // 撤消
self.window?.firstResponder?.undoManager?.undo()
return true
default:
return super.performKeyEquivalent(with: event)
}
}
}
小結
這節主要通過TextField
的實踐來加強對其的了解,常用的一些屬性和功能都包括在用,可以滿足大部分的場景。接下來我們學習NSButton
的使用。完整的項目源碼請訪問這里:https://github.com/dengyhgit/macOS-Dev-Demo/tree/master/NSTextField_Example, 如對你有幫忙,別忘點亮小??。