iOS 开发每天分享优质文章MacOS开发 技术集锦

macOS 开发-NSTextField 实践

2020-04-16  本文已影响0人  YxxxHao

这节主要通过实践来学习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的子类,因为我们希望他是单行可滚动的,所以需要设置isScrollabletrue

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时,把TextFieldcell指定为我们自定义的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, 如对你有帮忙,别忘点亮小⭐⭐。更多内容,请关注我的公众号:

关注公众号
上一篇 下一篇

猜你喜欢

热点阅读