缩进UITextField文本和占位符

时间:2019-04-28 05:38:33

标签: ios swift uitextfield

我已经在UITableView页脚中以编程方式创建了一个UITextField,如下所示:

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

我的问题是,如何缩进UITextField文本和占位符文本,使其不位于左侧边缘?

我发现了:

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

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以创建一个customTextField并覆盖文本,占位符,边框的矩形。基本上所有内容。

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)
    }
}

您可以通过更改x和y值来控制其位置