我正在嘗試在每個可在選定和未選中切換的uitableviewcell中創建一個複選框。爲了確保單個選擇在加載新單元格時不會回收,我創建了一個可變的字符串數組來表示「取消選中」或「檢查」(即,當按鈕圖像應該顯示爲未選中或被選中時)。當按下檢查按鈕時,字符串將被替換爲「檢查」或「取消選中」。出於某種原因,我無法看到,當tableview滾動並且選中的檢查按鈕的單元格離開屏幕時,數組將丟失對其所做的更改,因此檢查字符串將丟失。UITableviewcell中的複選框隨着表格滾動消失
任何想法有什麼不對?
在此先感謝您的幫助。
就在第一個單元格按鈕在「checkButtonClicked」檢查後selectedCheckArray的NSLog的: {檢查,取消選中,取消選中,取消選中,取消選中,取消選中,取消選中}
selectedCheckArray的的NSLog後,我向下滾動,從而即第一小區不再在屏幕上: {取消選中,取消選中,取消選中,取消選中,取消選中,取消選中,取消選中}
下面的代碼:
.H
@property (strong, nonatomic) NSMutableArray *selectedCheckArray;
.M
@synthesize selectedCheckArray;
...
- (void)viewWillAppear:(BOOL)animated
{
// cellDataArray loaded here
selectedCheckArray = [[NSMutableArray alloc] init];
for (int i = 0; i<[cellDataArray count]; i++) {
[selectedCheckArray addObject:@"Uncheck"];
}
[super viewWillAppear:animated];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [cellDataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"choiceCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIButton *checkButton = (UIButton *)[cell viewWithTag:1];
if ([[selectedCheckArray objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"]) {
[checkButton setImage:[UIImage imageNamed:@"unchecked"]
forState:UIControlStateNormal];
} else {
[checkButton setImage:[UIImage imageNamed:@"checked"]
forState:UIControlStateNormal];
}
[checkButton addTarget:self action:@selector(checkButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];
return cell;
}
...
- (void)checkButtonClicked:(id)sender
{
// indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:choiceTable];
NSIndexPath *indexPath = [choiceTable indexPathForRowAtPoint:touchPoint];
// Not using tag as sender will keep reference of clicked button
UIButton *button = (UIButton *)sender;
//Checking the condition button is checked or unchecked.
//accordingly replace the array object and change the button image
if([[selectedCheckArray objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
{
[button setImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
[selectedCheckArray replaceObjectAtIndex:indexPath.row withObject:@"Check"];
} else {
[button setImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
[selectedCheckArray replaceObjectAtIndex:indexPath.row withObject:@"Uncheck"];
}
}
你的'selectedCheckArray'被修改的唯一地方是在'checkButtonClicked:'?並在該方法中正確修改?我已經看到很多有趣的事情發生在用UITableView轉換點/幀的時候。 – MishieMoo
這似乎不是問題 - 我再次嘗試使用按鈕的超級視圖來獲取單元格,tableview和indexPath。該問題似乎與「replaceObjectAtIndex」。 – user1978374