Gabe Spound
Gabe Spound

Reputation: 146

Change the text layout in a UITextField

Below is an image of some UITextFields. Regarding the large one on the bottom, how do I get it to start text at the top left (not the middle), and how do I get them all to start a bit to the right. As you can see, they are awkwardly close to the left edge.


enter image description here

Upvotes: 0

Views: 1995

Answers (4)

Anbu.Karthik
Anbu.Karthik

Reputation: 82766

add left padding of your textfield

let paddingVie = UIView(frame: CGRect(x: 0, y:0, width: 10, height: 10))
yourtextField.leftView = paddingVie
yourtextField.leftViewMode = .always

for textview add

yourTextVieName.textContainerInset =
   UIEdgeInsetsMake(8,5,8,5); // top, left, bottom, right

Upvotes: 1

AlvinZhu
AlvinZhu

Reputation: 448

For textField, override following methods:

class InsetTextField: UITextField {

    var inset: CGFloat = 10

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: 0)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: 0)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: 0)
    }

}

For textView:

textView.contentInset = UIEdgeInsetsMake(inset, inset, inset, inset);

And you can be involved when the textView is done editing, check out this question.

Upvotes: 2

Subject X
Subject X

Reputation: 43

By default, UITextFields only have one line. Based off your image, I'd assume you want the user to have space to type a paragraph. For paragraphs, it is better to use UITextViews. It'd be a simpler solution for your problem.

I always use TextViews for biographies because it just makes my life much easier.

Upvotes: 1

aircraft
aircraft

Reputation: 26924

You can sublcass to a custom TextField:

import UIKit

class CustomTextField: UITextField {

    var inset:CGFloat = 12  // You can set the inset you want

    override func textRect(forBounds bounds: CGRect) -> CGRect {

        return bounds.insetBy(dx: inset, dy: 0)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {

        return bounds.insetBy(dx: inset, dy: 0)
    }

}

The result, you can see the inset of the CustomTextField:


Edit

enter image description here

Upvotes: 1

Related Questions