Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

ios - Insert string at cursor position of UITextField

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]  

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...