NSTextField是否与textField:shouldReplaceCharactersInRange等效?

时间:2018-12-29 10:19:45

标签: macos cocoa nstextfield nstextview

我想在NSTextField中捕获输入文本,然后对其进行更改和操作。

textField:shouldReplaceCharactersInRange的{​​{1}},并且 UITextField代表textView:shouldChangeTextInRange

更新: 我不介意NSTextView是否会被触发

2 个答案:

答案 0 :(得分:1)

当您的NSTextField成为焦点时,它将成为NSTextView的委托,被称为“字段编辑器”。结果,您的NSTextField可以符合NSTextViewDelegate协议,这意味着您可以像这样实现textView:shouldChangeTextInRange:replacementString:

@interface MyTextField : NSTextField <NSTextViewDelegate>
@end

@implementation MyTextField

- (BOOL)textView:(NSTextView *)textView 
  shouldChangeTextInRange:(NSRange)affectedCharRange 
  replacementString:(NSString *)replacementString
{
  // Do your thing.
}

@end

答案 1 :(得分:-1)

如何?

import Cocoa

class ViewController: NSViewController {

    @IBOutlet var textField: NSTextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        textField.delegate = self
    }
}

extension ViewController: NSTextFieldDelegate {

    func controlTextDidChange(_ obj: Notification) {
        if let textField = obj.object as? NSTextField {
            NSLog("%@", textField.stringValue)
            // how about set the textField's max length
            textField.stringValue = String(textField.stringValue.prefix(6))
        }
    }
}