如何解决UITextField 中的 borderRect、editingRect、placeholderRect、textRect 是什么?
从之前发布的 answer 中,我了解到 editingRect
是编辑文本时显示的矩形,而 textRect
是未编辑文本时显示的矩形。但我不知道 UITextField 控件中 placeholderRect
和 borderRect
的确切显示位置。我认为 borderRect
将与 UITextField 的框架矩形相同,因为其中包含“边框”一词,但在执行此操作后:
override func borderRect(forBounds bounds: CGRect) -> CGRect {
let rect = bounds
rect.size.height = 150 //the height of my UITextField currently is 100
return rect
}
我意识到它不是。那么什么是 placeholderRect
和 borderRect
,它们在 UITextField 中的位置是什么?
解决方法
borderRect
指的是边框的框架(如果 borderStyle != .none
,它将存在于文本字段中),而 placeholderRect
指的是占位符文本的框架 - 出现的文本当 text
为空时。
这是一个小示例,您可以将其粘贴到操场上,其中显示了所有矩形的位置。我为每个文本字段矩形返回了不同的 bounds
矩形。
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,height: bounds.height / 2)
}
override func borderRect(forBounds bounds: CGRect) -> CGRect {
// bottom left
CGRect(x: bounds.minX,y: bounds.midY,height: bounds.height / 2)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
// bottom right
CGRect(x: bounds.midX,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
输出:
,来自 Apple 文档:
placeholderRect(forBounds:) (Documentation)
返回文本字段占位符文本的绘图矩形
borderRect(forBounds:) (Documentation)
返回文本字段的边框矩形。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。