[英]Trying to disable a button when not all UITextFields are populated in iOS
我正在開發一個應用程序,其中有一個由自定義UITableViewCell組成的UITableView。 每個UITableViewCell都有一個UITextField。 我正在嘗試做的是在填充所有UITextField時啟用UIButton,我現在可以這樣做。 我現在的挑戰是,當不是所有的UITextField都被填充時,禁用此按鈕。 這是我正在使用的代碼:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
for (int i = 0; i < [self.table numberOfSections]; i++) {
NSInteger rows = [self.table numberOfRowsInSection:i];
for (int row = 0; row < rows; row++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:i];
SimpleTableCell *cell = (SimpleTableCell *)[self.table cellForRowAtIndexPath:indexPath];
NSNumber *numKey = [NSNumber numberWithInt: cell.dataField.tag];
NSString *text = cell.dataField.text;
if ([[cell dataField] text] != nil && [[[cell dataField] text] length] > 0) {
[_dict setObject:text forKey:numKey];
NSArray *keys = [_dict allKeys];
if ([keys count] == ([_dataName count] - 1)) { //where _dataName is the array that is populating my UITableView
[_doneButton setEnabled:YES];
[_doneButton.titleLabel setFont:[UIFont boldSystemFontOfSize:28]];
}
} else { //if there is a UITextField that is empty
[_dict removeObjectForKey:numKey];
NSArray *keys = [_dict allKeys];
//below is the clause where I disable the button, after checking if there is a single UITextField that is not populated
if ([keys count] < ([_tireName count] - 1)) {
[_doneButton setEnabled:NO];
[_doneButton.titleLabel setFont:[UIFont systemFontOfSize:28]];
}
}
}
}
return YES;
}
僅當填充了所有字段時,它才能夠啟用按鈕,這正是我想要的,但是不幸的是,它僅在有三個空的UITextField時才禁用按鈕。 我這樣做的方法是:
在遍歷UITableView中的每個UITextField時,我會檢查UITextField是否為空。 如果不為空,則使用UITextFields標記值作為鍵,將UITextField中的字符串值輸入到NSMutableDictionary中。 如果UITextField為空,則只需刪除連接到該鍵的對象。 從理論上講,我的方法是有道理的,但是它沒有按我希望的那樣工作。 誰能看到我在做什么錯?
當textField:shouldChangeCharactersInRange:replacementString:被調用時,textField的文本值尚未更改。 此方法用於確定在實際更改文本之前是否應允許用戶輸入文本。 因此,當您檢查文本是否為空時,正在編輯的文本字段將說它不為空,即使該文本字段將要變為空。
換句話說,如果您正在編輯其中包含“ A”的文本字段,並且用戶按下了退格鍵,則當您使用此方法檢查文本時,它將說它是“ A”,而不是“”。 因此,當您清除其中一個文本字段的文本時,將永遠不會禁用該按鈕。
從第二個文本字段中刪除文本時,它應該捕獲對前一個文本字段的更改,但是, if ([keys count] < ([_tireName count] - 1))
我可以確定應該禁用該按鈕是if([keys count] < [_tireName count])
同樣,我想您也想要if([keys count] == [_dataName count])
除非您實際上期望_dataName和_tireName總是比字典多記錄1條。
因為當字典中的鍵數少於[_tireName count] -1時將禁用該按鈕,因此除非您有2個空文本字段,否則您似乎永遠不會禁用該按鈕。
清除第二個文本字段后,一旦編輯了第三個文本字段,就會認為是時候該讓您最終禁用該按鈕了。
你可以嘗試改變
NSString *text = cell.dataField.text;
像這樣
NSString* text;
if(textfield == cell.dataField) //if this cell's textfield is the field we are editing
{
text = [cell.dataField.text stringByReplacingCharactersInRange:range withString:string];
}
else
{
text = cell.dataField.text;
}
這將防止您在進行驗證時查看正在編輯的文本字段的舊值。 然后將if([keys count] < (_tireName count] -1))
更改為if([keys count] < [_tireName count])
。
可能還有一種更改方式,您無需遍歷表視圖中的所有行,但是如果表視圖中只有8行,則這種更改將帶來很小的收益。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.