1

I have seen this post Text inset for UITextField? and am still not able to figure it out.

I want a UITextField that has is 80.0 tall. I want the text to be 40.0 below the top of the UITextField, 20.0 tall, leaving 20.0 below the text as padding. My current code is.

let textBounds: CGRect = CGRect(x: 0, y: 40, width: self.width, height: 20)
self.editingRectForBounds(textBounds)
self.textRectForBounds(textBounds)

The UITextField is subclassed and currently I believe the text has 30.0 padding above and below and is 20.0 tall or vertically centered within the UITextField.

Community
  • 1
  • 1
Cody Weaver
  • 4,756
  • 11
  • 33
  • 51

1 Answers1

0

I have rewritten your code to use a UITextField subclass:

class myTextField: UITextField {
    var textBounds: CGRect = CGRectZero

    override init(frame: CGRect) {
        super.init(frame: frame)
        textBounds = CGRectMake(0, 40, self.frame.width, 20)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return textBounds
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return textBounds
    }    
}

and added an example of how it might be added to your view:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let textField = myTextField(frame: CGRectMake(20, 64, 200, 50))
        textField.text = "Hello World"

         // Show a border to visualize the frame.
        textField.layer.borderColor = UIColor.redColor().CGColor
        textField.layer.borderWidth = 1

        view.addSubview(textField)
    }

}

The UITextField subclass can be added to your view controller file or to a separate file. It is your choice.

Daniel Zhang
  • 5,778
  • 2
  • 23
  • 28