Kle*_*son 16
这个答案很清楚,
如果你是子类,UITextField你可以覆盖textRectForBounds,editingRectForBounds和placeholderRectForBounds.这些方法只允许您在文本字段的标签中添加rect(框架).
newBounds 方法创建将添加到textfield标签的rect(框架).
最后你的填充是: let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);
现在您有一个自定义UITextField,它具有自定义填充.
class MyTextField: UITextField例如,如果您创建这样的新子类,则只需要更改已添加到IB文件中的UITextField的类.
Jor*_*ego 13
补充klevison-matias的答案这是我在Swift 3中向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)
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的TextField中我以这种方式使用:
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
}()
Run Code Online (Sandbox Code Playgroud)
Avi*_*are 11
创建TextField插座并使用以下代码.说"nameTextField"必须添加填充.
let paddingView = UIView(frame: CGRectMake(x: 0, y: 0, width: 30, height: 30))
nameTextField.leftView = paddingView
nameTextField.leftViewMode = .always
nameTextField.placeholder = "Enter Name"
Run Code Online (Sandbox Code Playgroud)
您可以在paddingView中添加Image.