gpt4 book ai didi

c# - NSTextField 下拉列表中显示建议

转载 作者:行者123 更新时间:2023-12-03 17:01:09 24 4
gpt4 key购买 nike

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

    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 将返回我需要与自动完成列表的数据源绑定(bind)的对象列表。 the required functionality sample如何在 Xamarin.Mac 中实现此目的?

最佳答案

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.CompleteChanged 方法保存:

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 协议(protocol)并返回您在上一步中保存的完成词:

[Export("control:textView:completions:forPartialWordRange:indexOfSelectedItem:")]
public string[] GetCompletions(NSControl control, NSTextView textView, string[] words, NSRange charRange, ref nint index)
{
requestor = null;
return completionWords;
`}

关于c# - NSTextField 下拉列表中显示建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51477805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com