From the answer previously posted, I understand that editingRect
is the rectangle shown when the text is being edited, and textRect
is the one shown when the text is not being edited. But I don't know where exactly placeholderRect
and borderRect
are displayed in a UITextField control. I assumed the borderRect
would be the same as the frame rect of UITextField because of the word 'border' in it, but after doing this:
override func borderRect(forBounds bounds: CGRect) -> CGRect {
let rect = bounds
rect.size.height = 150 //the height of my UITextField currently is 100
return rect
}
I realized it was not. So what are placeholderRect
and borderRect
, and where are they located in UITextField?
borderRect
refers to the frame of the border (which will exist for a text field if borderStyle != .none
), and placeholderRect
refers to the frame of the placeholder text - the text that appears when text
is empty.
Here is a little sample that you can paste into a playground, that shows where all the rects are. I returned different quarters the bounds
rect for each of the text field rects.
class TextFieldWithDifferentRects: UITextField {
override func textRect(forBounds bounds: CGRect) -> CGRect {
// top left
CGRect(x: bounds.minX, y: bounds.minY, width: bounds.width / 2, height: bounds.height / 2)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
// top right
CGRect(x: bounds.midX, y: bounds.minY, width: bounds.width / 2, height: bounds.height / 2)
}
override func borderRect(forBounds bounds: CGRect) -> CGRect {
// bottom left
CGRect(x: bounds.minX, y: bounds.midY, width: bounds.width / 2, height: bounds.height / 2)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
// bottom right
CGRect(x: bounds.midX, y: bounds.midY, width: bounds.width / 2, height: bounds.height / 2)
}
}
let view = TextFieldWithDifferentRects(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .white // make the placeholder text more visible
view.borderStyle = .line
view.placeholder = "a" // use the playground quick view button here
view.text = "b" // and here
// by selecting everything, we kick the text field into edit mode, to show the editingRect
view.selectAll(nil) // and lastly here
Output: