【问题标题】:In iOS, Cursor position is not able to update from the Started event using the "SelectedTextRange"在 iOS 中,光标位置无法使用“SelectedTextRange”从 Started 事件更新
【发布时间】:2022-01-10 12:11:37
【问题描述】:

说明

在 iOS 中,无法使用焦点上的“SelectedTextRange”属性从启动事件手动更新光标位置。请参考以下示例和屏幕截图。

复制步骤

  1. 创建自定义控件。
  2. 通过从 UITextField 继承来创建原生控件。
  3. Hook 以原生方式开始活动。
  4. 使用下面的代码 sn-p 从启动事件更新光标位置。 代码片段:
var positionToSet = this.GetPosition(this.BeginningOfDocument, 3);                      
if (positionToSet != null)                                                                
{                                                                                          
    this.SelectedTextRange = this.GetTextRange(positionToSet, positionToSet);               
}                                                                                
       (OR)
  1. 运行附加的示例。
  2. 光标应位于第三个索引(3 旁边),同时关注控件。

预期行为

光标应位于第三个索引处(3 旁边),如下图所示。

实际行为

光标位于最后。

示例: https://github.com/xamarin/Xamarin.Forms/files/7653944/CustomControl.zip

注意: 问题仅在 iOS 设备 14.4 或更高版本上重现。

【问题讨论】:

  • UI 更新应该在主线程中进行
  • @LeoDabus - OP 正在描述在 iOS.UITextView.Started 事件上运行的代码。我已经测试过,当此代码运行时,Xamarin.Essentials.MainThread.IsMainThread 为真。任何其他想法它可能是什么?我已经用断点确认 SelectedTextRange 被自定义代码更新为(位置 3,长度 0)。 (在模拟器上,iPhone 11 iOS 15.0)试图思考这如何无法影响显示。
  • 我很确定您需要在设置范围之前将队列分派到主线程
  • @LeoDabus 啊对。它在主线程上,但在一个动作的中间。如您所说,需要将其排队到主线程。

标签: ios swift xamarin.forms xamarin.ios uitextfield


【解决方案1】:

有必要对更改进行排队,以便在 Started 事件返回后发生:

CoreFoundation.DispatchQueue.MainQueue.DispatchAsync( () => {
    this.SelectedTextRange = this.GetTextRange(positionToSet, positionToSet);
});

基于Leo Dabus' answer in swift

在 iOS 模拟器、iPhone 11、iOS 15.0 上测试。

【讨论】:

  • 工作+1,在主线程中调用代码按预期工作。
  • 感谢@ToolmakerSteve,它正在工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2011-08-15
  • 2019-01-17
  • 1970-01-01
相关资源
最近更新 更多