Norway


Topics

Topics

is one of the sort of “low ” hidden gems of UIKit. Today we’ll look at some of the lesser-known things it can do and how to configure them. Let’s dive in.

We’ll begin by creating a text field and customizing its look and feel. First, instead of boring plain placeholder, let’s spice things up a bit:

let placeholder = NSMutableAttributedString()

placeholder.append(
  AttributedString(
    string: "Spaceship ",
    attributes: [NSFontAttributeName : boldFont]
  )
)

placeholder.append(
  AttributedString(
    string: "Name",
    attributes: [NSFontAttributeName : font]
  )
)

textField.attributedPlaceholder = placeholder

- 246 example 1 - #246: UITextField B-sides 📼 – Little Bites of Cocoa – Tips and techniques for iOS and Mac development

Nice, now let’s customize how our text field works.

Suppose we wanted to clear out its contents when a user tapped it. We simply set clearsOnBeginEditing to true.

Similarly, if we wanted to clear the contents not when the user tapped the field, but rather when the user began typing content, we can set clearsOnInsertion to true.

Let’s add some more “padding” to our text field. This turns out to be a tricker than expected.

UITextField allows for customization of the rects it uses to draw text via subclassing:

class PaddedTextField : UITextField {
  override func textRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: 16.0, dy: 8.0)
  }
}

Finally, we’d like allow users to fancy up (bold, italic, underline) the names of their spaceships. Turns out UITextField makes this super easy:

textField.allowsEditingTextAttributes = true

With attribute editing enabled, we now get this great editing rich-text UI for free. Neat!

- 246 example 2 - #246: UITextField B-sides 📼 – Little Bites of Cocoa – Tips and techniques for iOS and Mac development



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here