這節(jié)主要通過(guò)實(shí)踐來(lái)學(xué)習(xí)NSTextField的使用兼都,初步了解NSTextField的代理方法、常用屬性、常用樣式等內(nèi)容,完整代碼可以參看源碼目錄下的NSTextField_Example項(xiàng)目薇芝。
TextField Delegate
NSTextFieldDelegate
承繼于NSControlTextEditingDelegate
,實(shí)際常用的只有NSControlTextEditingDelegate
丰嘉,具體內(nèi)容如下:
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
以上的代碼方法看起來(lái)非常恩掷,但在實(shí)踐開(kāi)發(fā)中,大數(shù)用到的主要是下面三個(gè):
extension ViewController: NSTextFieldDelegate
{
/// 開(kāi)始編輯
func controlTextDidBeginEditing(_ obj: Notification) {
print("controlTextDidBeginEditing")
}
/// 結(jié)束編輯
func controlTextDidEndEditing(_ obj: Notification) {
print("controlTextDidEndEditing")
}
/// 內(nèi)容改變
func controlTextDidChange(_ obj: Notification) {
let textField = obj.object as? NSTextField
print("controlTextDidChange,text:" + (textField?.stringValue ?? ""))
}
}
TextField 常用屬性
我們可以通過(guò)查看NSTextField.h
文件供嚎,來(lái)獲取到 NSTextField
的常用屬性和方法有以下這些:
// 內(nèi)容為空時(shí)的提示文案
@property (nullable, copy) NSString *placeholderString;
// 內(nèi)容為空時(shí)的提示文案,富文本
@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;
// 選擇文本框時(shí)調(diào)用
- (void)selectText:(nullable id)sender;
// 設(shè)置代理
@property (nullable, weak) id<NSTextFieldDelegate> delegate;
// 是否允許開(kāi)始編輯文本框
- (BOOL)textShouldBeginEditing:(NSText *)textObject;
// 是否允許結(jié)束編輯文本框
- (BOOL)textShouldEndEditing:(NSText *)textObject;
// 文本框進(jìn)入編輯的通知
- (void)textDidBeginEditing:(NSNotification *)notification;
- (void)textDidEndEditing:(NSNotification *)notification;
// 文本框內(nèi)容發(fā)生變化的通知
- (void)textDidChange:(NSNotification *)notification;
// 獲取是否接受第一響應(yīng)
@property (readonly) BOOL acceptsFirstResponder;
// 設(shè)置貝塞爾風(fēng)格
@property NSTextFieldBezelStyle bezelStyle;
@property CGFloat preferredMaxLayoutWidth;
// 要顯示的最大行數(shù)。默認(rèn)值0表示沒(méi)有限制克滴。如果文本達(dá)到了允許的行數(shù)逼争,或者容器的高度不能容納所需的行數(shù),則文本將被剪切
@property NSInteger maximumNumberOfLines;
TextField文字居中
在前面內(nèi)容劝赔,已經(jīng)了解TextField
的基本使用誓焦,但是發(fā)現(xiàn)使用時(shí)發(fā)現(xiàn)TextField
中的文字沒(méi)有居中顯示,現(xiàn)在這我們來(lái)實(shí)現(xiàn)一個(gè)單行着帽、文字居中的TextField
杂伟。
在實(shí)現(xiàn)單行文字居中的效果前,我們需要先了解NSTextFieldCell
仍翰,它的作用是增強(qiáng)Cell的文本顯示功能的對(duì)象赫粥。
TextFieldCell
的文字默認(rèn)點(diǎn)貼著頂部邊框的,我們可以在TextFieldCell
渲染的時(shí)候予借,通過(guò)調(diào)用內(nèi)容的y
坐標(biāo)來(lái)調(diào)整文本的越平,首頁(yè)我選擇自定義一個(gè)承繼于NSTextFieldCell
的子類(lèi),因?yàn)槲覀兿M菃涡锌蓾L動(dòng)的灵迫,所以需要設(shè)置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")
}
}
接下來(lái)我們需要計(jì)算文字居中需要距離頂部的偏移量秦叛,以獲取文字居中的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后,我在文字繪制的時(shí)候調(diào)整其frame即可達(dá)到小居中的效果:
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)
}
}
我們實(shí)現(xiàn)了TextFieldCell
后瀑粥,在創(chuàng)建TextField
時(shí)挣跋,把TextField
的cell
指定為我們自定義的TextFieldCell
,即可以實(shí)現(xiàn)最終的效果:
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
本身是不會(huì)處理系統(tǒng)事件的狞换,如果在文本框中我們需要支持復(fù)制避咆、粘貼這類(lèi)事情,我們則需要單獨(dú)去監(jiān)聽(tīng)鍵盤(pán)事件哀澈。我們只需要重寫(xiě)NSResponder
中的performKeyEquivalent(with:)
:
// 處理按鍵事件
func performKeyEquivalent(with event: NSEvent) -> Bool
重寫(xiě)該方法以處理按鍵事件牌借。如果事件中的character code或codes與接收方的鍵值匹配,則接收方應(yīng)響應(yīng)事件并返回true割按。如果不重寫(xiě)膨报,該方法默認(rèn)返回false,什么也不做适荣。
了解performKeyEquivalent(with:)
的作用后现柠,我們只要重寫(xiě)該方法并通過(guò)按鍵值來(lái)做相應(yīng)的處理,卻可以實(shí)現(xiàn)相應(yīng)的快捷功能:
extension NSTextField {
override open func performKeyEquivalent(with event: NSEvent) -> Bool {
let modifierkeys = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
let key = event.characters ?? ""
/// 點(diǎn)擊 esc 取消焦點(diǎn)
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": // 復(fù)制
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)
}
}
}
小結(jié)
這節(jié)主要通過(guò)TextField
的實(shí)踐來(lái)加強(qiáng)對(duì)其的了解弛矛,常用的一些屬性和功能都包括在用够吩,可以滿(mǎn)足大部分的場(chǎng)景。接下來(lái)我們學(xué)習(xí)NSButton
的使用丈氓。完整的項(xiàng)目源碼請(qǐng)?jiān)L問(wèn)這里:https://github.com/dengyhgit/macOS-Dev-Demo/tree/master/NSTextField_Example周循, 如對(duì)你有幫忙强法,別忘點(diǎn)亮小??。