自定义TextField清除按钮

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

 1 //
 2 //  TextFieldDemoViewController.m
 3 //  OCDemo
 4 //
 5 //  Created by 思 彭 on 16/12/14.
 6 //  Copyright © 2016年 思 彭. All rights reserved.
 7 //
 8 
 9 #import "TextFieldDemoViewController.h"
10 
11 @interface TextFieldDemoViewController ()<UITextFieldDelegate>
12 
13 @property (nonatomic, strong) UITextField *textField;
14 
15 @end
16 
17 @implementation TextFieldDemoViewController
18 
19 - (void)viewDidLoad {
20     [super viewDidLoad];
21 
22     self.textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 100, 200, 35)];
23     self.textField.delegate = self;
24     self.textField.placeholder = @"请输入";
25     self.textField.borderStyle = UITextBorderStyleLine;
26     [self.view addSubview:self.textField];
27     
28     /*
29     self.textField.clearButtonMode = UITextFieldViewModeAlways;
30     // 设置textField清除按钮的背景颜色
31     [self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
32     // 不能改变背景颜色,需要设置imageView属性
33     [self.textField setValue:[UIColor redColor] forKeyPath:@"_clearButton.backgroundColor"];
34 //    [self.textField setValue:[UIImage imageNamed:@"iconfont-shuqian_sel_30x30_@2x"] forKeyPath:@"_clearButton.image"];
35     
36      */
37     
38     UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
39     clearButton.frame = CGRectMake(self.textField.frame.size.width - 10, 10, 10, 10);
40     [clearButton addTarget:self action:@selector(clearButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
41     [clearButton setImage:[UIImage imageNamed:@"iconfont-shuqian_sel_30x30_@2x"] forState:UIControlStateNormal];
42     [self.textField addSubview:clearButton];
43 }
44 
45 - (void)clearButtonDidClick: (UIButton *)button {
46     
47     self.textField.text = nil;
48 }
49 
50 - (BOOL)textFieldShouldReturn:(UITextField *)textField {
51     
52     [self.textField resignFirstResponder];
53     return YES;
54 }
55 @end

 

转载于:https://www.cnblogs.com/pengsi/p/6178755.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值