【问题标题】:Get row number of UITableView in IOS [duplicate]在IOS中获取UITableView的行号[重复]
【发布时间】:2013-07-19 10:11:11
【问题描述】:

在我的代码中,我有一个表格视图,其中许多部分按字母顺序排序。我在表格行中有checkboxes(UIButton),我需要根据在行中输入的相应状态检查它们。我已经完成了

checkbutton.tag = indexpath.row; 

但是当表格滚动和部分发生变化并且我在我的复选框方法中获得前一部分的状态时。任何人都请帮助我。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   CheckButton = [UIButton buttonWithType:UIButtonTypeCustom];
   [CheckButton addTarget:self action:@selector(CheckBoxAction:)      forControlEvents:UIControlEventTouchUpInside];
   CheckButton.tag=indexPath.row;
   //some other stuff
   [cell.contentView addSubview:CheckButton];
}

这是我的CheckBoxAction

-(void)CheckBoxAction:(UIButton *)btn
{
    tag = btn.tag;
    NSDictionary *tagdict =[statusArray objectAtIndex:tag]; 
}

现在,问题是 indexpath.row 在更改部分时为 0,因此我无法访问我的 CheckBoxAction 中的确切行号。

【问题讨论】:

  • 你为什么在那个事件中创建复选框按钮,而不是在 getCellForRowAtIndex 或界面生成器中?

标签: iphone ios objective-c uitableview


【解决方案1】:

使用它来获取您点击的当前行。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 CheckButton = [[UIButton alloc] init];

[CheckButton addTarget:self action:@selector(CheckBoxAction:)     forControlEvents:UIControlEventTouchUpInside];
CheckButton.tag=indexPath.row;
[cell addSubview:CheckButton];
}


-(void)CheckBoxAction:(id)sender
{
  // Cast Sender to UIButton
UIButton *button = (UIButton *)sender;

// Find Point in Superview
CGPoint pointInSuperview = [button.superview convertPoint:button.center toView:self.tableView];

// Infer Index Path
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInSuperview];

// Log to Console
NSLog(@"selected Row : %d", indexPath.row);
}

【讨论】:

    【解决方案2】:

    // 试试这个

    CheckButton.tag = [[NSString stringWithFormat:@"%d%d",indexPath.section,indexPath.row] integerValue];
    

    // 试试下面这个链接来获取逻辑,如何处理 UITableView 中的复选框

    Set checkmark in UITableView

    【讨论】:

    • 当节超过 9 并且节下的行超过 9 时,这将变得一团糟。
    【解决方案3】:

    你所做的在很多方面都是错误的。因此,我不会针对您遇到的确切问题为您提供解决方案,而是提供更多指导:

    1. 首先,您将复选框直接添加到单元格中,这意味着您可以在同一单元格中添加多个 CheckButton,如果您滚动 UITableView 几次。

    2. 直接在单元格上添加checkButton,而不是一直添加到cellForRowAtIndexPath,这样可以提高性能。

    3. 使用当用户单击按钮时将执行的块。这样您就可以捕获UIViewController 的上下文。您应该将该块分配给cellForRowAtIndexPath上的单元格

    【讨论】:

    • 你能解释一下如何直接在单元格上添加checkButton而不是继续在cellForRowAtIndexPath中添加它
    • 您可以在您的单元格中添加awakeFromNib。或者,如果您没有 NIB,您可以将它添加到您的单元格的 init 方法中。但同样,这不是您问题的具体答案,只是一个指导方针。
    • 先生,我听不懂。您能否提供一些链接、教程或任何类型的帮助以直接在单元格上添加 checkButton
    猜你喜欢
    • 2014-10-02
    • 2019-12-30
    • 2012-09-11
    • 2018-07-15
    • 2017-07-16
    • 1970-01-01
    • 2012-12-03
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多