Tether uilabel closely to the text being input to UITextField

12 Views Asked by At

I want the currency abbreviation uilabel closely follow text being input into UITextField. What's a good way to calculate where did the text being input ended so that

func rightViewRect(forBounds bounds: CGRect) -> CGRect

can calculate the label rect properly?

1

There are 1 best solutions below

0
On

Among other things I've ended up with this helper:

func rightViewRect(bounds: CGRect,
                   label: UILabel,
                   field: UITextField
    ) -> CGRect
{
    let measure = UILabel()
    measure.font = field.font
    if field.text?.isEmpty ?? true {
        measure.text = field.placeholder
    } else {
        measure.text = field.text
    }
    let cs = measure.intrinsicContentSize
    let lcs = label.intrinsicContentSize
    guard lcs.width > 0 else {
        return .zero
    }
    let magicSpace = CGFloat(2)
    let unclipped = CGRect(x: cs.width + magicSpace, y: 0, width: lcs.width, height: bounds.height)
    let clipped = unclipped.intersection(bounds)
    return clipped
}