UItextField leftViewのInstatsの設定
1393 ワード
Insetsはcssのpaddingです
テキスト入力ボックスの左側にアイコンを表示するために、UItextFieldにleftViewを設定しました.しかしios 7では、このアイコンはTextFieldの左枠にぴったりと隣接していて、美しくないので、Insetsを設定したいと思っています.ただしImageViewのboundsを直接設定することはできません.次の方法が必要です.
重要なのは、UItextFieldのサブクラスを定義し、leftViewRectForBoundsメソッドを上書きすることです.
テキスト入力ボックスの左側にアイコンを表示するために、UItextFieldにleftViewを設定しました.しかしios 7では、このアイコンはTextFieldの左枠にぴったりと隣接していて、美しくないので、Insetsを設定したいと思っています.ただしImageViewのboundsを直接設定することはできません.次の方法が必要です.
@interface YLSTextField : UITextField
-(id)initWithFrame:(CGRect)frame Icon:(UIImageView*)icon;
@end
@implementation YLSTextField
-(id)initWithFrame:(CGRect)frame Icon:(UIImageView*)icon
{
self = [super initWithFrame:frame];
if (self) {
self.leftView = icon;
self.leftViewMode = UITextFieldViewModeAlways;
}
return self;
}
-(CGRect) leftViewRectForBounds:(CGRect)bounds {
CGRect iconRect = [super leftViewRectForBounds:bounds];
iconRect.origin.x += 10;// 10
return iconRect;
}
@end
UIImage *usernameImage = [UIImage imageNamed:@"user"];
UIImageView *usernameIcon = [[UIImageView alloc] initWithImage:usernameImage];
usernameIcon.frame = CGRectMake(0, 0, 20, 20);
self.username = [[YLSTextField alloc] initWithFrame:CGRectMake(0, 0, 240, 30) Icon:usernameIcon];
self.username.placeholder = @" ";
self.username.borderStyle = UITextBorderStyleRoundedRect;
self.username.clearButtonMode = UITextFieldViewModeWhileEditing;
[self.username setKeyboardType:UIKeyboardTypeNumberPad];
重要なのは、UItextFieldのサブクラスを定義し、leftViewRectForBoundsメソッドを上書きすることです.