在UITextField的光标位置插入字符串 [英] Insert string at cursor position of UITextField

查看:587
本文介绍了在UITextField的光标位置插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a few UITextFields in an UITableView. The user should be able to insert only numbers and dots. To do this, I set the keyboard type to UIKeyboardTypeNumberPad and added a '.'-Button at the bottom left corner. Every time the button is pressed, a function is called. This function should insert a dot at the current cursor position, but this is the problem: UITextField hasn't got an selectedRange property, so I'm not able to get the current cursor position. Does anybody know how to solve this problem or is there any other way to do this? Thanks.

推荐答案

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

I've finally found a solution for this problem! You can put the text you need inserted into the system pasteboard and then paste it at the current cursor position:

[myTextField paste:self]  

我在此人的博客上找到了解决方案:

http://dev.ragfield.com/2009/09/insert-text-at-current-cursor -location.html

I found the solution on this person's blog:
http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html

粘贴功能是OS V3.0特定的,但我已经测试了它,它对我来说很好用自定义键盘。

The paste functionality is OS V3.0 specific, but I've tested it and it works fine for me with a custom keyboard.

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

Update: As per Jasarien's comment below, it is good practice to save off the pasteboard contents first and restore them afterward. For convenience, here is my code:

  // 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];

这篇关于在UITextField的光标位置插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆