我想插入一个UITextField的文本。
这可能吗?
我想插入一个UITextField的文本。
这可能吗?
当前回答
我在IB中做了这个,我在textView后面创建了一个UIView,它有点长。与textField背景颜色设置为清除。
其他回答
在从UITextField派生的类中,至少重写以下两个方法:
- (CGRect)textRectForBounds:(CGRect)bounds;
- (CGRect)editingRectForBounds:(CGRect)bounds;
如果你没有额外的内容,它可能就像这样简单:
return CGRectInset(bounds , 10, 10);
UITextField提供了几个可以覆盖的定位方法。
快速解决没有子类&也检查
extension UITextField {
@IBInspectable var textInsets: CGPoint {
get {
return CGPoint.zero
}
set {
layer.sublayerTransform = CATransform3DMakeTranslation(newValue.x, newValue.y, 0);
}
}
}
你可以通过使文本字段成为UITextField的子类并覆盖-textRectForBounds:方法来调整文本在文本字段中的位置。
Swift 3 /可在界面构建器中设计/单独的水平和垂直昆虫/可用
@IBDesignable
class TextFieldWithPadding: UITextField {
@IBInspectable var horizontalInset: CGFloat = 0
@IBInspectable var verticalInset: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: horizontalInset, dy: verticalInset)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: horizontalInset , dy: verticalInset)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: horizontalInset, dy: verticalInset)
}
}
用法:
&
Swift 4.2版本:
import UIKit
class InsetTextField: UITextField {
let inset: CGFloat = 10
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: inset, dy: inset)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: inset, dy: inset)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: inset, dy: inset)
}
}