title: Format UITextField text without having cursor move to the end
body: <p>I am trying to apply <strong>NSAttributedString</strong> styles to a <strong>UITextField</strong> after processing a new text entry, keystroke by keystroke. The problem is that any time I replace the text the cursor will jump the very end on each change. Here's my current approach …</p>
  
  <p>Receive and display text change immediately (same issue applies when I <em>return false</em> and do the text replacement manually)</p>
  
  <pre><code>func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -&gt; Bool {        
      let range:NSRange = NSRange(location: range.location, length: range.length)
      let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string);
      return true
  }
  </code></pre>
  
  <p>I subscribed to the UITextFieldTextDidChangeNotification notification. This triggers the styling. When the text is changed I replace it (<strong>NSString</strong>) with the formatted version (<strong>NSAttributedString</strong>) using some format() function.</p>
  
  <pre><code>func textFieldTextDidChangeNotification(userInfo:NSDictionary) {
      var attributedString:NSMutableAttributedString = NSMutableAttributedString(string: fullString)
      attributedString = format(textField.text) as NSMutableAttributedString
      textField.attributedText = attributedString
  }
  </code></pre>
  
  <p>Styling works fine like this. However after each text replacement the cursor jumps to the end of the string. How can I turn off this behaviour or manually move the cursor back where it started the edit? … or is there a better solution to style the text while editing?</p>