目前项目中需要用到自定义Cell及cell中的Acessory图片,期间碰到了一些不吐不快的槽,非常抱歉由于项目要赶进度,我只能每周挤点时间出来写写,让大家久等了,sorry。
// 设置Accessory UIImage *imageAccessory = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon_right" ofType:@"png"]]; UIButton *btnAccessory = [UIButton buttonWithType:UIButtonTypeCustom]; CGRect frame = CGRectMake(0.0f, 0.0f, imageAccessory.size.width, imageAccessory.size.height); btnAccessory.frame = frame; [btnAccessory setBackgroundImage:imageAccessory forState:UIControlStateNormal]; [btnAccessory setBackgroundImage:imageAccessory forState:UIControlStateHighlighted]; btnAccessory.backgroundColor = [UIColor clearColor]; [btnAccessory addTarget:self action:@selector(btnClicked:event:) forControlEvents:UIControlEventTouchUpInside]; NSLog(@"btnAccessory = %@", btnAccessory); cell.accessoryView = btnAccessory; NSLog(@"cell.accessoryView = %@", cell.accessoryView);
#pragma mark - IBAction Methods // 检查用户点击按钮时的位置,并转发事件到对应的accessory tapped事件 - (void)btnClicked:(id)sender event:(id)event { NSSet *touches = [event allTouches]; UITouch *touch = [touches anyObject]; CGPoint currentTouchPosition = [touch locationInView:tableViewCustom]; NSIndexPath *indexPath = [tableViewCustom indexPathForRowAtPoint:currentTouchPosition]; // or instead with such below // UITableViewCell *cell = (UITableViewCell *)sender.superview; if(indexPath != nil) { [self tableView:tableViewCustom accessoryButtonTappedForRowWithIndexPath:indexPath]; } }
UIImage图片位置必须正确,一次手误打错路径,浪费了2分钟在上面,建议nslog一下以免产生坑爹的空值。
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
关于UITableViewCellAccessoryType建议大家每一种都试一下,看看效果如何,但如果要自定义Accessory,这个方法基本上没啥鸟用。用了以后还有可能迷惑你=。=
自定义Accessory时直接使用以下代码是没用的
accessoryButtonTappedForRowWithIndexPath:indexPath
所以需要增加一个SEL
[btnAccessory addTarget:self action:@selector(btnClicked:event:) forControlEvents:UIControlEventTouchUpInside];个人觉得可以再UITableViewCellAccessoryType中再增加一个自定义类型,然后直接映射到这个方法,省得麻烦啊~
accessoryButtonTappedForRowWithIndexPath:indexPath
代码我会在周日前附上,先去吃饭了=。=