#import@interface SOInsetsLabel : UILabel@property(nonatomic)UIEdgeInsets insets;-(id)initWithFrame:(CGRect)frame andInsets: (UIEdgeInsets)insets;-(id)initWithInsets: (UIEdgeInsets)insets;@end
#import "SOInsetsLabel.h"@implementation SOInsetsLabel@synthesize insets=_insets;-(id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets)insets{ self = [super initWithFrame:frame]; if(self){ self.insets = insets; } return self;}-(id)initWithInsets:(UIEdgeInsets)insets{ self = [super init]; if(self){ self.insets = insets; } return self;}-(void)drawTextInRect:(CGRect)rect { return [super drawTextInRect:UIEdgeInsetsInsetRect(rect,self.insets)];}@end
#import@interface SOInsetsTextField : UITextField@end
#import "SOInsetsTextField.h"@implementation SOInsetsTextField//控制placeHolder 的位置,左右缩 20- (CGRect)textRectForBounds:(CGRect)bounds { return CGRectInset( bounds , 20 , 0 );}//控制文本的位置,左右缩 20- (CGRect)editingRectForBounds:(CGRect)bounds { return CGRectInset( bounds , 20 , 0 );}@end
//下面是使用 InsetsTextField 的代码,可放在 viewDidLoad 等代理方法中
InsetsTextField *insetTextField = [[InsetsTextField alloc] initWithFrame:CGRectMake(10,10, 180, 25)];//须手动设置它的 borderStyle, 不然看不到边框的insetsTextField.borderStyle = UITextBorderStyleRoundedRect;[self.view addSubview:insetsTextField];
效果如下: Unmi InsetsTextField上面更像是借鉴的 InsetsLabel 的实现,其实对于 UITextField 还有更好的实现办法,而且更简单,因为 UITextFiled 原来就支持的做法。比如它可以让你做出在文本框最前方固定一个 $ 符号,表示这个文本框是输入钱的,第一个$ 是不能被删除的。确实,你可以在 TextField 上贴个 Label,然后文本框的光标后移,稍显麻烦了。而 UITextField 可以直接设置 leftView 或 rightView, 然后文本输入区域就在 leftView 和 rightView 之间了,看例子:
UILabel *paddingView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 10, 25)];paddingView.text = @"$";paddingView.textColor = [UIColor darkGrayColor];paddingView.backgroundColor = [UIColor clearColor];textfield.leftView = paddingView;textfield.leftViewMode = UITextFieldViewModeAlways;