使用xcode中的swift设置文本字段的填充

sek*_*san 11 ios swift

如何使用swift在文本字段的开头创建一些空间?我看了看帖子

填充文本字段

我不明白子类正在做什么以及如何使用该类填充.

非常感谢你

Kle*_*son 16

/sf/answers/1894673511/

这个答案很清楚,

  1. 如果你是子类,UITextField你可以覆盖textRectForBounds,editingRectForBoundsplaceholderRectForBounds.这些方法只允许您在文本字段的标签中添加rect(框架).

  2. newBounds 方法创建将添加到textfield标签的rect(框架).

  3. 最后你的填充是: let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);

  4. 现在您有一个自定义UITextField,它具有自定义填充.

  5. 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.