0

In objective-C, I can make my subclass of NSTextField conform to the the NSTextViewDelegate protocol - like so:

@interface PasswordField : NSTextField <NSTextViewDelegate>

How can I translate this idiom to C# / monomac?

I have tried subclassing NSTextViewDelegate:

private class TextViewDelegate : NSTextViewDelegate
{}

And assigning that to the delegate property of my NSTextField subclass:

public class PasswordField : NSTextField
{
    public PasswordField(NSCoder coder) : base(coder)
    {
        this.Delegate = new TextViewDelegate();
    }
}

However, obviously this does not work since the Delegate property of NSTextField is (correctly) typed as NSTextFieldDelegate.

Error CS0029: Cannot implicitly convert type `PasswordFieldControl.PasswordField.TextViewDelegate' to `MonoMac.AppKit.NSTextFieldDelegate' (CS0029)

So how to make this work as it does in objective-C?

TheNextman
  • 12,428
  • 2
  • 36
  • 75

1 Answers1

1

There are two ways to do this:

If you are fine with keeping the delegate separate, you can do this:

class TextViewDelegate : NSTextViewDelegate
{
    public override void TextDidChange (NSNotification notification)
    {
    }
}

public class PasswordField : NSTextField
{
    public PasswordField(NSCoder coder) : base(coder)
    {
        this.WeakDelegate = new TextViewDelegate();
    }
}

or, if you want to use the same PasswordField object:

public class PasswordField : NSTextField
{
    [Export("textDidChange:")]
    public void TextDidChange (NSNotification notification)
    {
    }

    public PasswordField(NSCoder coder) : base(coder)
    {
        this.WeakDelegate = this;
    }
}
Curtis
  • 1,552
  • 15
  • 20
  • Yes, I stated that in my question. In Objective-C, it is possible for subclassed NSTextField to conform to the NSTextViewDelegate protocol. I want to know how to recreate that idiom in C#/MonoMac. – TheNextman Feb 22 '13 at 15:56
  • If you really want to do this, assign it to .WeakDelegate instead of .Delegate, though I recommend against that. You will have to apply the [Export(...)] attribute to your delegate methods. – Curtis Feb 22 '13 at 19:33
  • Thank you, I was not aware of the WeakDelegate property. I will give this a try next week and let you know how it works out. – TheNextman Feb 22 '13 at 21:25