NSTextField的建议显示在下拉列表中

时间:2018-07-23 11:33:59

标签: c# cocoa xamarin xamarin.mac

我正在尝试使用NSTextField来实现自动完成功能,用户将在其中键入一些字符串,并将从API提取建议以显示在文本字段下。 (可选)在文本字段内显示进度指示器。到目前为止,我已经在Xcode IB中设计了UI,并钩住了该事件以获取文本更改事件。

    public class UserTextFieldDelegate: NSTextFieldDelegate
    {
        public NSTextField Username { get; set; }
        public UserTextFieldDelegate()
        {
        }
        public UserTextFieldDelegate(NSTextField username)
        {
            this.Username = username;
        }
        public override void Changed(NSNotification notification)
        {
            Console.WriteLine(Username.StringValue);
        }
    }

API将返回我需要与自动完成列表的数据源绑定的对象列表。 the required functionality sample 如何在Xamarin.Mac中实现此目标?

1 个答案:

答案 0 :(得分:2)

NSTextField.Changed中,从NSNotification参数中保存NSTextView并调用Rest API:

NSString NSFieldEditor = new NSString("NSFieldEditor");
NSTextView editor;
[Export("controlTextDidChange:")]
public void Changed(NSNotification notification)
{
    editor = editor ?? notification.UserInfo.ObjectForKey(NSFieldEditor) as NSTextView;
    SomeRestCall(nsTextField.StringValue);
}

现在,使用Rest方法,通过后台队列调用实际的Rest api,并保存/缓冲字符串数组中返回的完成词,然后对从{{保存的NSTextView实例变量}调用NSTextView.Complete 1}}方法:

Changed

string[] completionWords = { }; void SomeRestCall(string search) { if (editor != null) { DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Background).DispatchAsync(() => { if (string.IsNullOrWhiteSpace(search)) completionWords = new string[] { }; else // Fake a REST call... completionWords = (new string[] { "sushi", "stack", "over", "flow" }) .Where((word) => word.StartsWith(search, StringComparison.CurrentCulture)).ToArray(); if (editor != null) DispatchQueue.MainQueue.DispatchAsync(() => { editor?.Complete(null); }); }); } } 的实现中,添加INSTextFieldDelegate协议并返回在上一步中保存的完成词:

GetCompletions