Train
Train

Reputation: 3496

how to print formated text from keyboard

I was wondering how can I print formated text from the keyboard keys. For example, I have a toolbar attached to the keyboard, I click "bold" on the keyboard and from there on every letter printed from the keyboard will now be bold. This is what I have but it does not work, String's don't seem to hold format.

  func keyPressed(sender: AnyObject?) {
       let button = sender as! UIButton
       let title = button.titleForState(.Normal)

       let attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15)]
       let boldString = NSMutableAttributedString(string:title!, attributes:attrs)


       (textDocumentProxy as UIKeyInput).insertText(boldString.string)
  }

Upvotes: 0

Views: 162

Answers (1)

TwoStraws
TwoStraws

Reputation: 13127

Strings don't hold format, you're right. You should manipulate your target directly, using NSAttributedString and attributedText to do so.

let str = "Hello, world!"
let attrs = [NSFontAttributeName: UIFont.systemFontOfSize(15)]

let attributedString = NSAttributedString(string: str, attributes: attrs)
yourTextView.attributedText = attributedString

Note that the specific thing you want to do is tricky, because attributed strings attach attributes (like bold) to parts of text and not "from there on every letter". So if you read out the current attributed string then try to modify the attributes at the caret without actually inserting anything, it won't work.

So, this won't work:

let existingAttributedString = yourTextView.attributedText.mutableCopy() as! NSMutableAttributedString
let newAttrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(15)]
let newAttributedString = NSAttributedString(string: "", attributes: newAttrs)
existingAttributedString.appendAttributedString(newAttributedString)

Whereas this will:

let existingAttributedString = yourTextView.attributedText.mutableCopy() as! NSMutableAttributedString
let newAttrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(15)]
let newAttributedString = NSAttributedString(string: " ", attributes: newAttrs)
existingAttributedString.appendAttributedString(newAttributedString)

The only difference is that the second example inserts a space, which is enough for iOS to attach attributes to.

That being said, if you're willing to change your approach so that users select existing text before hitting bold, that works great.

Upvotes: 1

Related Questions