我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
当前回答
^这些建议对于那些通过编程方式创建界面的人来说非常有用。
但是对于我们这些使用Xcode界面构建器的人来说,有两个LAZY EASY方法:
更简单:把一个UIImageView放在一个文本字段后面 最简单的方法:将边框样式更改为简单的黑色正方形(左起第二个选项),然后将图像添加为背景图像。图像优先于正方形,因此您仍然可以获得正常图像背景所需的填充,而不需要实际绘制正方形。
编辑:你也可以使用黑色球体(在IB中选择UITextBox时,左起第三个选项),它不适合最右边的“图形球体”风格。
其他回答
你不能设置填充。而是有一个UIView,里面有你的背景图像和UITextField。设置UITextField的宽度为UIViewWidth-(paddingSize x 2)和高度相似,然后设置它在点paddingSize,paddingSize。
我发现了一个整洁的小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
以下是如何在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
}
}
资源
Objective C代码
MyTextField.h
#import <UIKit/UIKit.h>
@interface MyTextField : UITextField
@property (nonatomic) IBInspectable CGFloat padding;
@end
MyTextField.m
#import "MyTextField.h"
IB_DESIGNABLE
@implementation MyTextField
@synthesize padding;
-(CGRect)textRectForBounds:(CGRect)bounds{
return CGRectInset(bounds, padding, padding);
}
-(CGRect)editingRectForBounds:(CGRect)bounds{
return [self textRectForBounds:bounds];
}
@end
为UITextField添加填充的一个好方法是子类化并添加一个edgeInsets属性。然后设置edgeInsets和UITextField将相应地绘制。对于自定义的leftView或rightView集,这也能正确地发挥作用。
OSTextField.h
#import <UIKit/UIKit.h>
@interface OSTextField : UITextField
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
OSTextField.m
#import "OSTextField.h"
@implementation OSTextField
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsZero;
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
self.edgeInsets = UIEdgeInsetsZero;
}
return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
@end