码迷,mamicode.com
首页 > 其他好文 > 详细

自定义TextField清除按钮

时间:2016-12-14 14:05:54      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:order   void   font   import   copyright   pat   code   role   dcl   

当需要设置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

 

自定义TextField清除按钮

标签:order   void   font   import   copyright   pat   code   role   dcl   

原文地址:http://www.cnblogs.com/pengsi/p/6178755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!