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?
Calculate UITextField baseline position
Asked Answered
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)
© 2022 - 2024 — McMap. All rights reserved.