【问题标题】:How to call an action from a Custom UITableViewCell for reload tableView如何从自定义 UITableViewCell 调用操作以重新加载 tableView
【发布时间】:2011-05-17 21:21:03
【问题描述】:

我有一个简单的问题:我无法在UITableViewCell .m 中从UIButton 调用"[tableView reloadData]"

我有一个tableView,它显示每行包含UIButtonUITableViewCell。当我点击单元格的按钮时,我想从我的 tableView 中重新加载数据。

【问题讨论】:

    标签: iphone uitableview uibutton reloaddata


    【解决方案1】:

    只要您持有对 tableView 的引用,您就应该能够通过点击按钮重新加载数据。最简单的方法是在头文件中进行引用

    @interface MyClass ... {
        UITableView *myTableView;
        // all your other stuff;
    }
    // any methods and properties you want to declare;
    @end
    

    然后,当您在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法中将按钮放入单元格时,请执行以下操作

    UIButton *myButton = [UIButton buttonWithType:whateverTypeYouPick];
    [myButton addTarget:self action:@selector(reloadTableView) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:myButton];  // or cell.contentView or wherever you want to place it
    

    然后简单地设置你的操作方法

    - (IBAction)reloadTableView {
        [myTableView reloadData];
        // anything else you would like to do;
    }
    

    我对此进行了测试,它对我来说效果很好,所以希望它也对你有用

    【讨论】:

    • 谢谢提示,我现在试试并回复结果:)
    • 非常感谢 slev,它真的帮了我很多 ^^。我只在 cellForRowAtIndexPath 上更改了这部分:方法:code( [cell.myButton addTarget:self action:@selector(reloadTableView:) forControlEvents:UIControlEventTouchUpInside]; return cell; })
    • 太棒了。我很高兴它对你有用。祝你好运,我很高兴能帮上忙 =]
    【解决方案2】:

    其中一种方法是在 Cell 上设置委托,并在操作发生时让 tableViewController 实现委托。

    MyCell.h

    @protocol MyCellDelegate
    
    -(void)myCell:(MyCell*)cell reloadTableView:(id)sender;
    
    @end
    
    @interface MyCell : UITableViewCell
    
    @property (nonatomic, weak) id <MyCellDelegate> delegate;
    
    -(IBAction)reloadTableView:(id)sender;
    
    @end
    

    MyCell.m

    @implementation MyCell
    
    @property (nonatomic, weak) id <MyCellDelegate> delegate;
    
    -(IBAction)reloadTableView:(id)sender;
    {
        if(self.delegate)
        {
            [self.delegate myCell:self reloadTableView:sender];
        }
    }
    
    @end
    

    在tableViewController中实现委托方法,做你想做的任务。

    -(void)myCell:(MyCell*)cell reloadTableView:(id)sender;
    {
         CGPoint location = [sender locationInView:self.tableView];
         NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
        //Here is the indexPath
        [self.tableView reloadData];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多