Calculate UITextField baseline position
Asked Answered
A

1

11

I'm trying to programmatically align the baseline of an instance of UITextField with an instance of UIButton. I'm currently handling this calculation similar way described here, but with UITextField there can be an offset to the content. Any ideas how could I get the text position within UITextField or even better, is there a more simple way to align the baselines?

Aqueduct answered 16/12, 2012 at 21:19 Comment(0)
L
0

In my experience, UITextField does not actually have any offset around the text, unlike UIButton. Regardless, you can figure out the exact text box in both controls:

let textField = UITextField()
//... size the field, e.g. textField.sizeToFit()

let button = UIButton()
//... size the button, e.g. button.sizeToFit()

// Compute the target offset between tops (frame.origin.y).
let buttonBox = button.contentRectForBounds(button.bounds)
let buttonBaseline = buttonBox.origin.y + button.titleLabel!.font.ascender

let textFieldBox = textField.textRectForBounds(textField.bounds)
let textFieldBaseline = textFieldBox.origin.y + textField.font!.ascender

let offset = buttonBaseline - textFieldBaseline

//... position button, e.g., button.frame = CGRect(...)

textField.frame = CGRect(
    origin: CGPoint(x: button.frame.maxX, y: button.frame.origin.y + offset),
    size: textField.bounds.size)

Example alignment with different font sizes

Lawrence answered 24/3, 2016 at 21:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.