0

I was using this post as reference: Create space at the beginning of a UITextField. And in this post, there is a very helpful class adding padding in a textfield. However, the only way that I know how to use this class is for me to programmatically create a textfield. But instead, I would like to use this class with an IBOutlet. Here is the TextField Class:

class TextField: UITextField {

    let padding = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 5);

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return self.newBounds(bounds)
    }

    override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        return self.newBounds(bounds)
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return self.newBounds(bounds)
    }

    private func newBounds(bounds: CGRect) -> CGRect {
        print("paisjdpfij")
        var newBounds = bounds
        newBounds.origin.x += padding.left
        newBounds.origin.y += padding.top
        newBounds.size.height -= padding.top + padding.bottom
        newBounds.size.width -= padding.left + padding.right
        return newBounds
    }
}

And here is my attempt to use it with my IBOutlet:

@IBOutlet weak var firstNameTextField: TextField!

override func viewDidLoad() {
    super.viewDidLoad()

    firstNameTextField = TextField()

}

However, the there is still no padding in the textfield. Anybody have a solution to this problem?

Now, I used this code:

let paddingView = UIView(frame: CGRect(x: 0.0, y: 10.0, width: 5.0, height: 20.0))

        firstNameTextField.leftView = paddingView
        firstNameTextField.leftViewMode = .Always

to add padding on the left side of the textfield. However, I would also like some padding on the bottom as well. And there doesn't seem to be a simple solution for adding a bottom padding.

Community
  • 1
  • 1
aejhyun
  • 612
  • 1
  • 6
  • 19

1 Answers1

0

you can create category/extension or create custom text field as you did. And implement this 2 methods and play with it by changing different bounds.

import UIKit

class CustomTextField: UITextField 
{

    required init?(coder aDecoder: NSCoder){
        super.init(coder: aDecoder)
    }

    override func textRectForBounds(bounds: CGRect) -> CGRect 
    {
        return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8, bounds.size.width - 20, bounds.size.height - 16);
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect 
    {
        return self.textRectForBounds(bounds);
    }
}

For more detail you can refer this Nate Flink's answer at here:Set padding for UITextField with UITextBorderStyleNone

Community
  • 1
  • 1
Mehul Thakkar
  • 12,440
  • 10
  • 52
  • 81