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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章