简体   繁体   中英

Indent UITextField text and placeholder

I have programmatically created a UITextField in my UITableView footer like so:

let customView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 50))

self.textArea = UITextField(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width - 50, height: 50))
self.textArea.placeholder = "Add Item"
self.textArea.layer.borderColor = UIColor.gray.cgColor
self.textArea.layer.borderWidth = 1
customView.addSubview(self.textArea)

let button = UIButton(frame: CGRect(x: self.view.bounds.width - 50, y: 0, width: 50, height: 50))
button.setTitle("Add", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = UIColor(displayP3Red: 3.0 / 255.0, green: 0.0  / 255.0, blue: 113.0  / 255.0, alpha: 1.0)
button.addTarget(self, action: #selector(self.addWishListItem), for: .touchUpInside)
customView.addSubview(button)

self.tableView.tableFooterView = customView

My question is, how do I indent the UITextField text and placeholder text so it's not right at the edge of the left side?

I found this:

let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: self.textArea.frame.height))
            self.textArea.leftView = paddingView
            self.textArea.leftViewMode = .always

Is there a better way on doing this?

You can create a customTextField and override the rects for text, placeholder, border.. basically everything.

import UIKit
class CustomTextField: UITextField {

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect.init(x: 10, y: -10, width: bounds.width, height: bounds.height)
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect.init(x: 10, y: -10, width: bounds.width, height: bounds.height)
    }
}

You control the position of it by changing x and y values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM