【问题标题】:Adding buttons on tableview - can't access the sender在 tableview 上添加按钮 - 无法访问发件人
【发布时间】:2012-07-01 19:44:04
【问题描述】:

我已使用以下代码向我的 tableviewcell 添加按钮,当按下按钮时,我需要知道它是哪一行。所以我标记了按钮(playButton viewWithTag:indexPath.row) 问题是,如果我定义目标操作方法(播放)来接收发送者,它会因“无法识别的选择器”而崩溃,任何想法如何知道按钮在哪一行被按下或为什么它会像这样崩溃 谢谢

-(void)configureCell: (UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom] ;
[playButton setFrame:CGRectMake(150,5,40,40)];
[playButton viewWithTag:indexPath.row] ; //Tagging the button
[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];
[cell addSubview:playButton];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *beatCell = nil;
beatCell = [tableView dequeueReusableCellWithIdentifier:@"beatCell"];
if (beatCell == nil){
    beatCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"beatCell"];
}
 [self configureCell:beatCell atIndexPath:indexPath];
return beatCell;

}

-(void) play:(id) sender{
UIButton *play = sender;
NSLog(@"Play %i" , play.tag);

}

【问题讨论】:

    标签: xcode uitableview uibutton sender


    【解决方案1】:

    代替

    [playButton viewWithTag:indexPath.row] ; 
    

    如果您尝试接收 UIButton 的子视图(我不知道为什么),您应该使用 setter 方法设置标签:

    [playButton setTag:indexPath.row];
    

    您还必须将您的发件人转换为 UIButton 类型

    -(void) play:(id) sender{
    UIButton *play = (UIButton *)sender;
    NSLog(@"Play %i" , play.tag);
    }
    

    【讨论】:

    • 谢谢,您的添加非常重要,因为我刚刚得到零,现在它正在工作!!!!
    【解决方案2】:

    改变这一行的一个字符:

    [playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];
    

    [playButton addTarget:self action:@selector(play:) forControlEvents: UIControlEventTouchUpInside];
    

    当您在选择器上包含参数时,冒号实际上对于 Objective C 运行时能够在您的目标对象上查找该选择器很重要。

    【讨论】:

    • 谢谢迈克尔,这很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多