Swift - 出现清除按钮时禁用文本移动
Swift - Disable text shifting when clear button appears
我的项目中有一个 UITextField,在编辑期间启用了清除按钮。
框内任何居中的文本都会向左移动,以便为焦点上的清除按钮腾出空间。我可以禁用这种转移吗?我觉得它很分散注意力。
请看下面的截图:
Is it possible for me to disable this shifting
只要用心一点,是的,你一定能做到。文本的绘制实际上取决于您,如果您将 UITextField 子类化:您可以覆盖 drawText(in:)
and/or textRect(forBounds:)
并负责文本的位置。
为了解决这个问题,我对 UITextField
进行了子类化,并将以下内容添加到子类中:
class CustomTextField: UITextField {
override func editingRectForBounds(bounds: CGRect) -> CGRect {
let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return UIEdgeInsetsInsetRect(bounds, padding)
}
}
Swift 4.2 & Xcode 10
class CustomTextField: UITextField {
override func editingRect(forBounds bounds: CGRect) -> CGRect {
let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return bounds.inset(by: padding)
}
}
在此处找到答案:Create space at the beginning of a UITextField
我的项目中有一个 UITextField,在编辑期间启用了清除按钮。
框内任何居中的文本都会向左移动,以便为焦点上的清除按钮腾出空间。我可以禁用这种转移吗?我觉得它很分散注意力。
请看下面的截图:
Is it possible for me to disable this shifting
只要用心一点,是的,你一定能做到。文本的绘制实际上取决于您,如果您将 UITextField 子类化:您可以覆盖 drawText(in:)
and/or textRect(forBounds:)
并负责文本的位置。
为了解决这个问题,我对 UITextField
进行了子类化,并将以下内容添加到子类中:
class CustomTextField: UITextField {
override func editingRectForBounds(bounds: CGRect) -> CGRect {
let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return UIEdgeInsetsInsetRect(bounds, padding)
}
}
Swift 4.2 & Xcode 10
class CustomTextField: UITextField {
override func editingRect(forBounds bounds: CGRect) -> CGRect {
let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return bounds.inset(by: padding)
}
}
在此处找到答案:Create space at the beginning of a UITextField