自定义TextField清除按钮

时间:2022-10-26 21:51:32
自定义TextField清除按钮

当需要设置TextField的清除按钮的时候,系统的总是不满足需求,这就需要我们自定义了,代码如下:

 //
// TextFieldDemoViewController.m
// OCDemo
//
// Created by 思 彭 on 16/12/14.
// Copyright © 2016年 思 彭. All rights reserved.
// #import "TextFieldDemoViewController.h" @interface TextFieldDemoViewController ()<UITextFieldDelegate> @property (nonatomic, strong) UITextField *textField; @end @implementation TextFieldDemoViewController - (void)viewDidLoad {
[super viewDidLoad]; self.textField = [[UITextField alloc]initWithFrame:CGRectMake(, , , )];
self.textField.delegate = self;
self.textField.placeholder = @"请输入";
self.textField.borderStyle = UITextBorderStyleLine;
[self.view addSubview:self.textField]; /*
self.textField.clearButtonMode = UITextFieldViewModeAlways;
// 设置textField清除按钮的背景颜色
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
// 不能改变背景颜色,需要设置imageView属性
[self.textField setValue:[UIColor redColor] forKeyPath:@"_clearButton.backgroundColor"];
// [self.textField setValue:[UIImage imageNamed:@"iconfont-shuqian_sel_30x30_@2x"] forKeyPath:@"_clearButton.image"]; */ UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
clearButton.frame = CGRectMake(self.textField.frame.size.width - , , , );
[clearButton addTarget:self action:@selector(clearButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
[clearButton setImage:[UIImage imageNamed:@"iconfont-shuqian_sel_30x30_@2x"] forState:UIControlStateNormal];
[self.textField addSubview:clearButton];
} - (void)clearButtonDidClick: (UIButton *)button { self.textField.text = nil;
} - (BOOL)textFieldShouldReturn:(UITextField *)textField { [self.textField resignFirstResponder];
return YES;
}
@end