我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
当前回答
为什么不是带属性字符串!?!,这是IOS 6.0的祝福功能之一:)
NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
mps.firstLineHeadIndent = 5.0f;
UIColor *placeColor = self.item.bgColor;
textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];
其他回答
我发现使用不可编辑的UITextView并设置contenttoffset要容易得多
uiTextView.contentOffset = CGPointMake(8, 7);
以下是如何在SWIFT中实现这一点
@IBOutlet weak var yourTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let paddingView = UIView(frame: CGRectMake(0, 0, 10, self.yourTextField.frame.height))
yourTextField.leftView = paddingView
yourTextField.leftViewMode = UITextFieldViewMode.Always
}
}
资源
我发现了一个整洁的小hack来设置左侧填充的确切情况。
基本上,你设置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
到目前为止,我找到的最佳解决方案是分类。这就是我如何在左右两侧添加5点填充:
@implementation UITextField (Padding)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 5, bounds.origin.y,
bounds.size.width - 10, bounds.size.height);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
#pragma clang diagnostic pop
@end
#pragma’s只是用来删除恼人的警告
为什么不是带属性字符串!?!,这是IOS 6.0的祝福功能之一:)
NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
mps.firstLineHeadIndent = 5.0f;
UIColor *placeColor = self.item.bgColor;
textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];