開發中很多這種情況,就是頁面中有一些需要填寫的信息,然後有一個按鈕,當頁面中的textFeild 還未填寫完整時,按鈕是不可點擊的狀態,填寫完整後纔可以點擊,該怎麼實現呢,實現思路:
因爲頁面中先填寫哪個textField是不一定的,所以我需要給每個textFeild 添加監聽事件,當編輯狀態改變時,去判斷頁面中所有的textFeild 是否都已經有值,有值則改變按鈕的可點擊狀態
由於項目中可能有很多頁面都會用到判斷的方法,所以我們可以把方法封裝起來,在用到的地方直接調取就行
上代碼(創建一個類,封裝方法):
//判斷是否有值,只要有NO,就爲灰色,如果都爲yes,那就直到最後一個都爲yes時,即爲yes
+ (void)setButtonStatusBytextFeilds:(NSArray *)textFeildArr button:(UIButton *)button{
for (UITextField *textF in textFeildArr) {
if (textF.text.length <= 0) {
[button setBackgroundColor:kLineColor];
button.enabled = NO;
return;
}else{
if ([(UITextField *)textFeildArr[textFeildArr.count - 1] text] > 0) {
[button setBackgroundColor:kGreenColor];
button.enabled = YES;
}
}
}
}
在用到的地方:
//給每個textFeild 添加監聽
self.textFArr = @[_passordF,_surePasswordF];
for (UITextField *textF in _textFArr) {
[textF addTarget:self action:@selector(setBtnStatus) forControlEvents:(UIControlEventEditingChanged)];
}
//調取判斷方法
- (void)setBtnStatus{
[ShowTool setButtonStatusBytextFeilds:_textFArr button:_registerBtn];
}
效果圖: