简体   繁体   English

按下回车键后如何在带有MonoMac的NSTextField中插入回车符?

[英]How to insert a carriage return in a NSTextField with MonoMac upon pressing the return key?

After reading this question together with this accepted answer , I tried to implement the given Objective-C solution with MonoMac in C#: 在阅读完此问题以及可接受的答案后 ,我尝试使用C#中的MonoMac实现给定的Objective-C解决方案:

- (BOOL)control:(NSControl*)control
    textView:(NSTextView*)textView
    doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;

    if (commandSelector == @selector(insertNewline:))
    {
        // new line action:
        // always insert a line-break character and don’t cause the receiver
        // to end editing
        [textView insertNewlineIgnoringFieldEditor:self]; 
        result = YES;
    }

    return result;
}

I managed to assign a delegate to my text box and override the DoCommandBySelector method. 我设法将委托分配给我的文本框并重写DoCommandBySelector方法。 What I did not manage is to translate the line 我没有管理的是翻译线

if (commandSelector == @selector(insertNewline:))

and the line 和线

[textView insertNewlineIgnoringFieldEditor:self]; 

into a C# equivalent, even after doing hours of try-and-error, together with lots of those "Google searches", everyone is talking about. 甚至经过数小时的反复尝试,再加上大量的“ Google搜索”,都变成了C#。

So my question is: 所以我的问题是:

How to translate the above two lines into a working MonoMac C# code? 如何将以上两行转换为有效的MonoMac C#代码?

OK, after another bunch of tries-and-errors, I came up with the following working solution. 好的,经过一堆反复尝试后,我想出了以下可行的解决方案。

This is where I assign the delegate to the text field: 这是我将委托分配给文本字段的地方:

textMessage.Delegate = new MyTextDel();

And this is the actual delegate definition: 这是实际的委托定义:

private class MyTextDel : NSTextFieldDelegate
{
    public override bool DoCommandBySelector (
        NSControl control, 
        NSTextView textView, 
        Selector commandSelector)
    {
        if (commandSelector.Name == "insertNewline:") {
            textView.InsertText (new NSString (Environment.NewLine));
            return true;
        }

        return false;
    }
}

So to answer my own question, the line: 所以要回答我自己的问题,该行:

if (commandSelector == @selector(insertNewline:))         // Objective-C.

translates to: 转换为:

if (commandSelector.Name == "insertNewline:")             // C#.

And the line: 和线:

[textView insertNewlineIgnoringFieldEditor:self];         // Objective-C.

translates (roughly) to: 大致翻译为:

textView.InsertText (new NSString (Environment.NewLine)); // C#.

I do hope that this is working under all circumstances, my first tests look promising. 我确实希望这在所有情况下都有效,我的第一个测试看起来很有希望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM