自定義UITextField類
#import "WZTextField.h"
@implementation WZTextField
// 修改文本展示區(qū)域,一般跟editingRectForBounds一起重寫
- (CGRect)textRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-25, bounds.size.height);//更好理解些
return inset;
}
// 重寫來編輯區(qū)域颖御,可以改變光標起始位置寓落,以及光標最右到什么地方,placeHolder的位置也會改變
-(CGRect)editingRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-25, bounds.size.height);//更好理解些
return inset;
}
//修改rightView的位置
- (CGRect) rightViewRectForBounds:(CGRect)bounds {
CGRect textRect = [super rightViewRectForBounds:bounds];
textRect.origin.x -= 10;
return textRect;
}
@end
在控制器中的使用:
- (void)viewDidLoad {
[super viewDidLoad];
WZTextField *tfView = [[WZTextField alloc]initWithFrame:CGRectMake(50, 50, 200, 30)];
//? ? tfView.backgroundColor = [UIColor grayColor];
//提示文字
tfView.placeholder = @"輸入商品";
//圓角
//? ? tfView.keyboardAppearance = UIKeyboardAppearanceAlert;
//改用layer圓角
tfView.layer.cornerRadius = 12;
tfView.layer.borderWidth = 1;
tfView.layer.borderColor = [UIColor colorWithRed:38/255.0 green:187/255.0 blue:155/255.0 alpha:1.0]
.CGColor;
tfView.tintColor = [UIColor redColor];
tfView.layer.masksToBounds = YES;
//? ? tfView.text = @"初始化文字";
//右邊的x號,點擊清除輸出 如果設置了rightView 會被覆蓋
tfView.clearButtonMode = UITextFieldViewModeWhileEditing;
//.rightView
UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
leftView.image = [UIImage imageNamed:@"search"];
tfView.rightView =leftView;
tfView.rightViewMode = UITextFieldViewModeAlways;
[self.view addSubview:tfView];
}