Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save mumer92/03a0444afee9d5f247ad0b2914c9eac3 to your computer and use it in GitHub Desktop.

Select an option

Save mumer92/03a0444afee9d5f247ad0b2914c9eac3 to your computer and use it in GitHub Desktop.

Revisions

  1. @nicklockwood nicklockwood revised this gist Jan 23, 2022. 1 changed file with 6 additions and 3 deletions.
    9 changes: 6 additions & 3 deletions UITextField+TrailingPlaceholder.swift
    Original file line number Diff line number Diff line change
    @@ -14,9 +14,12 @@ extension UITextField {
    }
    label.font = self.font
    label.frame = self.textRect(forBounds: self.bounds)
    label.frame.origin.x = (self.text ?? "").size(withAttributes: [
    .font: self.font as Any
    ]).width
    if self.window?.screen.scale == 3 {
    // Fix for slight baseline misalignment on @3x displays
    label.frame.origin.y -= 0.333
    }
    let size = (self.text ?? "").size(withAttributes: self.defaultTextAttributes)
    label.frame.origin.x = size.width
    label.isHidden = !self.hasText
    }, for: .editingChanged)
    }
  2. @nicklockwood nicklockwood created this gist Jan 23, 2022.
    23 changes: 23 additions & 0 deletions UITextField+TrailingPlaceholder.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import UIKit

    extension UITextField {
    /// Add a trailing placeholder label that tracks the text as it changes
    func addTrailingPlaceholder(_ placeholder: String) {
    let label = UILabel()
    label.text = placeholder
    label.alpha = 0.3
    label.isHidden = true
    addSubview(label)
    addAction(UIAction { [weak self] _ in
    guard let self = self else {
    return
    }
    label.font = self.font
    label.frame = self.textRect(forBounds: self.bounds)
    label.frame.origin.x = (self.text ?? "").size(withAttributes: [
    .font: self.font as Any
    ]).width
    label.isHidden = !self.hasText
    }, for: .editingChanged)
    }
    }