2016-12-06 54 views
1

我有一個tableview,其值可能相同。突出顯示選定的tableViewCell以匹配UITextfield.text

當選擇的單元格,文本字段值將與所選擇的小區來填充。

我只想強調的是選擇,而不是強調一切都是一樣的文本框的值的行。

我目前的做法:

其中data是可能的值

數組
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
    reuseIdentifier:@"identifierCell"]; 
} 

NSString *value = ([self.data objectAtIndex:indexPath.row]); 
NSString *selectedValue = textField.text; 

if ([value floatValue] == [selectedValue floatValue]) { 
    cell.backgroundColor = [UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0]; 
    cell.textLabel.textColor = [UIColor whiteColor]; 
} 
else { 
    cell.backgroundColor = [UIColor clearColor]; 
    cell.textLabel.textColor = [UIColor blackColor]; 
} 

附註:我有一對夫婦,這些降下來領域,可以改變文本框的文字取決於哪一行是選擇。 (即,如果第1行中的其他下拉列表中選擇,然後1.391將在文本框的文本填充。

不知道如何相關,這將是。

我怎麼會只檢查選擇和填充行?下面

enter image description here

更新每個圖像的文本框:感謝@ k06a使用indexPath是向前邁進了一步,但是現在問題就出現在那裏,如果選擇行A時,B用indexPath不應該更改。我想設置2個不同的indexPath變量和didSelectRowAt只設置那些我打電話來改變其他相應的值

enter image description here

方法
+0

您可以使用'UITableView'' allowsMultipleSelection'屬性實現多個單元格的選擇。 – k06a

回答

1

您可以列舉一個循環內的所有小區選擇和取消選擇行基於selectedValuevalue平等。該循環將取消選擇前一行,並選擇一個新行。不要忘記在離開可重用單元之後設置初始狀態。所有的細胞可以與提取:self.tableView.visibleCells

或者,你可以通過記住其indexPath取消先前的細胞。並選擇一個新的並記住它的indexPath。這是最有效的變體。

或者你可以撥打[self.tableView reloadData]當想改變選擇。這將不太有效,但更短,更容易實施。

UPDATE:

只要使用的不是立足於價值單元選擇,但其基礎上indexPath不同的條件。並提醒我爲什麼你需要手動選擇細胞?我的意思是手動設置backgroundColortextColor可以通過[UITableViewCell setSelected:]自動選擇。

+0

你可以展示請示例嗎?我並不完全遵循前兩種方法。 – Simon

+0

我手動設置單元格,因爲我有3個文本框框。它們中的每一個在選擇時爲tableview填充不同的值。當點擊行時,所有值都會變爲被點擊的行。我嘗試了你展示的'setSelected'方法,但沒有成功。 – Simon

+0

'indexPath'是一個前進的步驟,但我忘了提及其他要求。以上更新 – Simon

1

我的解決方案感謝@ k06a

NSIndexPath *selectedIndexPathA; 
NSIndexPath *selectedIndexPathB; 

didSelectRowAtIndexPath我通過在indexPath的方法,將設置這些值:

[self setOtherFieldsWithIndexPath:indexPath]; 

setOtherFieldsWithIndexPath方法

if (rowA) { selectedIndexPathA = indexPath; } 
else if (rowB) { selectedIndexPathB = indexPath; } 
else {...} 

然後終於在cellForRowAtIndexPath

if (selectedIndexPathA.row == indexPath.row) { 
    cell.backgroundColor = [UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0]; 
    cell.textLabel.textColor = [UIColor whiteColor]; 
} 
else if (selectedIndexPathB.row == indexPath.row) { 
    cell.backgroundColor = [UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0]; 
    cell.textLabel.textColor = [UIColor whiteColor]; 
} 
else { 
    cell.backgroundColor = [UIColor clearColor]; 
    cell.textLabel.textColor = [UIColor blackColor]; 
} 

不知道這是最好的解決辦法,但是,它目前的工作,我希望它的工作方式。