iOS5动态地为UITableViewCell中的附件按钮分配动作

Ale*_*one 1 iphone delegation selector uitableview ios5

我在应用程序中有一个表视图,我希望应用程序的多个部分可以用来将更新发布到表视图,并提供用户可以采取的操作.我想到实现这个的方法之一是通过一个大的枚举,带有表视图的switch语句.在这种情况下,表视图将基于表格单元格的枚举值执行操作.这需要了解所涉及的类,并且看起来过于复杂.

一定有更好的方法.是否可以使用具有UITableViewCell附件按钮目标的选择器?

我认为对于常规按钮和导航栏按钮,我可以这样做:

[thisIconBtn addTarget:self action:@selector(changeIconState:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

是否有相同的方法为 UITableView配件分配一个动作?或者我应该坚持使用大枚举?

谢谢!

cho*_*own 6

不幸的是,accessoryAction一个UITableViewCell被弃用的iOS 3.0.
来自UITableViewCell参考文档:

accessoryAction
选择器定义在用户点击附件视图时要调用的操作消息.(在iOS 3.0中不推荐使用.而是使用tableView:accessoryButtonTappedForRowWithIndexPath:处理单元格上的点按.)

但是,如果附件视图继承自UIControl(UIButton等),则可以通过该addTarget:action:forControlEvents:方法设置目标和操作.

像这样的东西(修改以满足您的需求):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
    }

    // Set the accessoryType to None because we are using a custom accessoryView
    cell.accessoryType = UITableViewCellAccessoryNone;

    // Assign a UIButton to the accessoryView cell property
    cell.accessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    // Set a target and selector for the accessoryView UIControlEventTouchUpInside
    [(UIButton *)cell.accessoryView addTarget:self action:@selector(someAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

或者,更传统的路线(我不是肯定的,但我相信你的问题表明这是你要避免的.如果这是真的,你可以忽略这段代码.):

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    // <statements>
                    break;
                case 1:
                    // <statements>
                    break;
                default:
                    // <statements>
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                    // <statements>
                    break;
                case 1:
                    // <statements>
                    break;
                default:
                    // <statements>
                    break;
            }
            break;
        default:
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)