UITableViewCell 內建的 checkmark 樣式雖然方便,但在需要更完整視覺設計時,往往不夠用。此時可以把 cell 的 accessoryView 替換成自訂的 UIButton,再透過圖片切換呈現勾選與未勾選狀態。
在 cellForRowAtIndexPath 中建立一個透明背景的 UIButton,並將它指定給 cell.accessoryView。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height); [button setBackgroundImage:image forState:UIControlStateNormal]; [button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside]; button.backgroundColor = [UIColor clearColor]; cell.accessoryView = button;
由於 accessoryView 上的按鈕點擊不會直接觸發 didSelectRowAtIndexPath,因此需要自行換算觸碰位置,取得對應的 index。
- (void)checkButtonTapped:(id)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
if (indexPath != nil) {
[self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}
}在資料中記錄每一列的勾選狀態,再依狀態切換 checked.png 與 unchecked.png,即可做出自訂樣式的勾選效果。
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
BOOL checked = [[item objectForKey:@"checked"] boolValue];
[item setObject:[NSNumber numberWithBool:!checked] forKey:@"checked"];
UITableViewCell *cell = [item objectForKey:@"cell"];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = checked ? [UIImage imageNamed:@"unchecked.png"] : [UIImage imageNamed:@"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
}