您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發:將 UITableView 預設勾選改為自訂圖像

編輯:iOS 開發綜合

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];
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved