How do you create textfield padding in Swift 4?

后端 未结 3 1818
太阳男子
太阳男子 2021-02-06 04:59

I have a textfield called

nameTextField

I rounded the corners with the

nameTexfield.layer.cornerRadius = 5

3条回答
  •  执笔经年
    2021-02-06 05:19

    As @the4kman says, Swift does support CGRect but the syntax may have changed.

    You can try this for instance:

    @IBOutlet weak var nameTextField: UITextField! {
        didSet {
            nameTextField.layer.cornerRadius =  5
            nameTextField.layer.borderColor = UIColor.black.cgColor
            nameTextField.layer.borderWidth = 1
            let leftView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 2.0))
            nameTextField.leftView = leftView
            nameTextField.leftViewMode = .always
        }
    }
    

    If I do that, I get this fine result

    Hope that helps.

    Update

    You ask for a function instead of setting it in didSet and sure, thats possible, something like:

    func addPaddingAndBorder(to textfield: UITextField) {
        textfield.layer.cornerRadius =  5
        textfield.layer.borderColor = UIColor.black.cgColor
        textfield.layer.borderWidth = 1
        let leftView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 2.0))
        textfield.leftView = leftView
        textfield.leftViewMode = .always
    }
    

    and then you' call that in viewDidLoad for instance like so:

    override func viewDidLoad() {
        super.viewDidLoad()
        addPaddingAndBorder(to: nameTextField)
    }
    

提交回复
热议问题