https://stackoverflow.com/a/27066764/846780
这个答案很清楚,
UITextField
,textRectForBounds
和editingRectForBounds
。这些方法只允许您在文本字段的标签中添加rect(框架)。placeholderRectForBounds
方法创建将添加到textfield标签的rect(框架)。newBounds
let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);
,则只需要更改已添加到IB文件中的UITextField的类。class MyTextField: UITextField
补充klevison-matias的答案这是我在Swift 3中向TextField添加填充时使用的代码
然后在我的TextField中我以这种方式使用:
//UITextField : override textRect, editingRect
class LeftPaddedTextField: UITextField {
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width, height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width, height: bounds.height)
}
}
创建TextField插座并使用以下代码。说“nameTextField”必须添加填充。
let emailTextField: LeftPaddedTextField = {
let textField = LeftPaddedTextField()
textField.placeholder = "Enter email"
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 1
textField.keyboardType = .emailAddress
return textField
}()
let passwordTextField: LeftPaddedTextField = {
let textField = LeftPaddedTextField()
textField.placeholder = "Enter password"
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 1
textField.isSecureTextEntry = true
return textField
}()
您可以在paddingView中添加Image。
根据@Jorge Casariego的回答,我提出了这个解决方案。
您可以通过Interface Builder设置let paddingView = UIView(frame: CGRectMake(x: 0, y: 0, width: 30, height: 30))
nameTextField.leftView = paddingView
nameTextField.leftViewMode = .always
nameTextField.placeholder = "Enter Name"
类和所需的填充!
PaddedTextField
完整代码示例:确保您的文本字段通过Storyboard指向圆角文本字段
class PaddedTextField: UITextField {
@IBInspectable var padding: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + padding, y: bounds.origin.y, width: bounds.width - padding * 2, height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + padding, y: bounds.origin.y, width: bounds.width - padding * 2, height: bounds.height)
}
}