简体   繁体   English

缩进UITextField文本和占位符

[英]Indent UITextField text and placeholder

I have programmatically created a UITextField in my UITableView footer like so: 我已经在我的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

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? 我的问题是,如何缩进UITextField文本和占位符文本,使其不在左侧的边缘?

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. 您可以创建customTextField并覆盖文本,占位符,边框的rects。基本上所有内容。

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 您可以通过更改x和y值来控制它的位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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