这篇文章介绍了如何使用NSTextField进行macOS开发,包括NSTextField的代理方法、常用属性、常用样式等内容,还介绍了如何实现单行文字居中、快捷键支持等功能。文章最后提供了完整的源代码。
此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结
投诉这节主要通过实践来学习NSTextField的使用,初步了解NSTextField的代理方法、常用属性、常用样式等内容,完整代码可以参看源码目录下的NSTextField_Example项目。
本文为转载文章,以下内容来源于
macOS 开发-NSTextField 实践
YxxxHao
TextField Delegate
NSTextFieldDelegate
承继于NSControlTextEditingDelegate
,实际常用的只有NSControlTextEditingDelegate
,具体内容如下:
1 2 3 4 5 6 7 8 9 10
| 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
|
以上的代码方法看起来非常,但在实践开发中,大数用到的主要是下面三个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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
的常用属性和方法有以下这些:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| @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;
@property NSInteger maximumNumberOfLines;
|
TextField文字居中
在前面内容,已经了解TextField
的基本使用,但是发现使用时发现TextField
中的文字没有居中显示,现在这我们来实现一个单行、文字居中的TextField
。
在实现单行文字居中的效果前,我们需要先了解NSTextFieldCell
,它的作用是增强Cell
的文本显示功能的对象。
TextFieldCell
的文字默认点贴着顶部边框的,我们可以在TextFieldCell
渲染的时候,通过调用内容的y坐标来调整文本的,首页我选择自定义一个承继于NSTextFieldCell
的子类,因为我们希望他是单行可滚动的,所以需要设置isScrollable
为true
:
1 2 3 4 5 6 7 8 9
| 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:
1 2 3 4 5 6 7 8
| 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即可达到小居中的效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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
,即可以实现最终的效果:
1 2 3 4 5 6 7 8
| 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:)
:
1 2
| func performKeyEquivalent(with event: NSEvent) -> Bool
|
重写该方法以处理按键事件。如果事件中的character code或codes与接收方的键值匹配,则接收方应响应事件并返回true。如果不重写,该方法默认返回false,什么也不做。
了解performKeyEquivalent(with:)
的作用后,我们只要重写该方法并通过按键值来做相应的处理,却可以实现相应的快捷功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| extension NSTextField { override open func performKeyEquivalent(with event: NSEvent) -> Bool { let modifierkeys = event.modifierFlags.intersection(.deviceIndependentFlagsMask) let key = event.characters ?? "" if modifierkeys.rawValue == 0 && key == "\u{1B}" { self.window?.makeFirstResponder(nil) } 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) } } }
|
源代码
源代码
张洪Heo
分享设计与科技生活
本文是转载或翻译文章,版权归原作者所有。建议访问原文,转载本文请联系原作者。