我想为我的UITextFields使用一个自定义的背景。除了我必须使用UITextBorderStyleNone使它看起来更漂亮之外,它工作得很好。这会强制文本在没有任何填充的情况下粘贴到左侧。
除了使用我的自定义背景图像之外,我可以手动设置一个填充,使其看起来与UITextBorderStyleRoundedRect相似吗?
发布于 2010-12-13 04:20:41
我找到了一个巧妙的小技巧来为这种情况设置左填充。
基本上,将UITextField的leftView属性设置为所需填充大小的空视图:
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;对我来说就像一个护身符!
在Swift 3/ Swift 4中,可以这样做
let paddingView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 20))
textField.leftView = paddingView
textField.leftViewMode = .always发布于 2011-06-21 03:16:25
我创建了这个类别实现,并将其添加到.m文件的顶部。
@implementation UITextField (custom)
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8,
bounds.size.width - 20, bounds.size.height - 16);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
@end基于Piotr Blasiak提供的链接。它看起来比创建一个全新的子类更简单,也比添加额外的UIView更简单。尽管如此,似乎还是缺少一些不能控制文本字段中的填充的东西。
Swift 4解决方案:
class CustomTextField: UITextField {
struct Constants {
static let sidePadding: CGFloat = 10
static let topPadding: CGFloat = 8
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(
x: bounds.origin.x + Constants.sidePadding,
y: bounds.origin.y + Constants.topPadding,
width: bounds.size.width - Constants.sidePadding * 2,
height: bounds.size.height - Constants.topPadding * 2
)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.textRect(forBounds: bounds)
}
}发布于 2014-12-19 02:28:31
适用于Xcode >6的Swift 3版本,其中您可以在Interface Builder / Storyboard中编辑插入值。
import UIKit
@IBDesignable
class FormTextField: UITextField {
@IBInspectable var inset: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: inset, dy: inset)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}

https://stackoverflow.com/questions/3727068
复制相似问题