在UITextField的光标位置插入字符串

Wet*_*ish 12 cocoa-touch uitextfield ios

我在UITableView中有一些UITextFields.用户应该只能插入数字和点.为此,我将键盘类型设置为UIKeyboardTypeNumberPad,并在左下角添加了一个"."按钮.每次按下按钮,都会调用一个函数.此函数应在当前光标位置插入一个点,但这是问题:UITextField没有selectedRange属性,因此我无法获取当前光标位置.有人知道如何解决这个问题,还是有其他方法可以做到这一点?谢谢.

Dan*_*n J 33

我终于找到了解决这个问题的方法!您可以将需要插入的文本放入系统粘贴板,然后将其粘贴到当前光标位置:

[myTextField paste:self]  
Run Code Online (Sandbox Code Playgroud)

我在这个人的博客上找到了解决方案:
http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html

粘贴功能是特定于OS V3.0的,但我已经测试过,它可以通过自定义键盘为我工作.

更新:根据下面Jasarien的评论,最好先保存粘贴板内容,然后再恢复它们.为方便起见,这是我的代码:

  // Get a reference to the system pasteboard
  UIPasteboard* lPasteBoard = [UIPasteboard generalPasteboard];

  // Save the current pasteboard contents so we can restore them later
  NSArray* lPasteBoardItems = [lPasteBoard.items copy];

  // Update the system pasteboard with my string
  lPasteBoard.string = @"-";

  // Paste the pasteboard contents at current cursor location
  [myUIField paste:self];

  // Restore original pasteboard contents
  lPasteBoard.items = lPasteBoardItems;

  [lPasteBoardItems release];
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的解决方案.但是,这里值得一提的是,在将内容放入粘贴板之前需要先保存用户的粘贴板内容,然后再恢复用户的内容.通过这种方式,他们不知道您使用了粘贴板,并且您的代码是一个好公民,而不是破坏用户粘贴板的内容. (5认同)

ohh*_*hho 10

- (void)insertText:(NSString *)text

适用于iOS 3.2及更高版本.