【发布时间】:2019-04-14 19:20:53
【问题描述】:
【问题讨论】:
-
我觉得这个答案可以帮到你stackoverflow.com/a/46730692/8231150
【问题讨论】:
https://stackoverflow.com/a/27066764/846780
这个答案很明确,
如果您继承 UITextField,您可以覆盖 textRectForBounds、editingRectForBounds 和 placeholderRectForBounds。这些方法只允许您向文本字段的标签添加一个矩形(框架)。
newBounds 方法创建将添加到文本字段标签的矩形(框架)。
最后你的填充是:let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);
现在您有了一个具有自定义填充的自定义 UITextField。
例如,如果您像 class MyTextField: UITextField 这样创建新的子类,您只需更改已添加到 IB 文件中的 UITextField 的类。
【讨论】:
补充 klevison-matias 的答案,这是我想在 Swift 3 中向我的 TextField 添加填充时使用的代码
//UITextField : override textRect, editingRect
class LeftPaddedTextField: UITextField {
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width, height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width, height: bounds.height)
}
}
然后在我的 TextField 中我以这种方式使用:
let emailTextField: LeftPaddedTextField = {
let textField = LeftPaddedTextField()
textField.placeholder = "Enter email"
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 1
textField.keyboardType = .emailAddress
return textField
}()
let passwordTextField: LeftPaddedTextField = {
let textField = LeftPaddedTextField()
textField.placeholder = "Enter password"
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 1
textField.isSecureTextEntry = true
return textField
}()
【讨论】:
创建 TextField 插座并使用以下代码。说“nameTextField”必须添加填充。
let paddingView = UIView(frame: CGRectMake(x: 0, y: 0, width: 30, height: 30))
nameTextField.leftView = paddingView
nameTextField.leftViewMode = .always
nameTextField.placeholder = "Enter Name"
您可以在 paddingView 中添加 Image。
【讨论】:
根据@Jorge Casariego 的回答,我想出了这个解决方案。
您可以通过 Interface Builder 设置 PaddedTextField 类和所需的填充!
class PaddedTextField: UITextField {
@IBInspectable var padding: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + padding, y: bounds.origin.y, width: bounds.width - padding * 2, height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + padding, y: bounds.origin.y, width: bounds.width - padding * 2, height: bounds.height)
}
}
【讨论】:
完整的代码示例: 确保您的 TextField 通过故事板指向 RoundedTextField
import UIKit
class RoundedTextField: UITextField {
override func awakeFromNib() {
// add rounded corner
self.layer.cornerRadius = 15.0
self.clipsToBounds = false
super.awakeFromNib()
}
// For the padding from the left
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 15.0, y: bounds.origin.y, width: bounds.width, height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 15.0, y: bounds.origin.y, width: bounds.width, height: bounds.height)
}
}
【讨论】: