iOS 自定制UITextField的clearButton

背景:
UITextFieldrightView被占用的时候,clearButtonMode就失效了,这时就需要自定制一个clearBtn了,要想实现和系统clearBtn一样的效果还得多调试一下,下面是我写好的跟系统一样效果的代码:

//遵守协议
<UITextFieldDelegate>

//创建clearBtn
UIView * phoneRight = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100*ScaleX+30, 40*ScaleX)];
UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[clearBtn addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
[clearBtn setImage:[UIImage imageNamed:@"clearImg"] forState:UIControlStateNormal];
clearBtn.frame = CGRectMake(5, 15, 15, 15);
[phoneRight addSubview:clearBtn];
self.clearBtn = clearBtn;
self.clearBtn.hidden = YES;

//textField 设置代理
_phoneTF.delegate = self;

//添加点击事件
- (void)clearAction {
    _phoneTF.text = @"";
    self.clearBtn.hidden = YES;
}

#pragma mark =============== UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([textField isEqual:_phoneTF] && textField.text.length > 0) {
        self.clearBtn.hidden = NO;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField isEqual:_phoneTF]) {
        
        if (range.location == 0 && range.length == 1 && string.length == 0) {
            self.clearBtn.hidden = YES;
        }else if (range.location > 0 || range.length > 0 || string.length > 0) {
            self.clearBtn.hidden = NO;
        }
    }
    return YES;
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if ([textField isEqual:_phoneTF]) {
        self.clearBtn.hidden = YES;
    }
    return YES;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值