如何从uibutton的发送者选项中获取价值

时间:2015-12-04 11:08:15

标签: ios objective-c iphone uibutton

我创建了一个自定义表格视图单元格,上面有一个按钮,同一文件tableviewcell.m中的按钮target(base calsee UITableViewCell)。

当我点击按钮时,会调用动作。

我要做的是从该按钮的sender选项中获取值。如图所示,想获得“badgesname”的值。

enter image description here

5 个答案:

答案 0 :(得分:1)

当您想要从单元格中跟踪某些其他事件时,应该做什么,而不仅仅是默认选择。例如,您添加了一些按钮。

  • 使用UIView的{​​{1}}属性错误使用标签阅读代码并不容易。当你不仅有行而是有部分时,你会做什么?
  • 查找tag为 您按钮的UITableViewCell 太差了! 按钮可以添加为直接superview子视图或单元格的UITableViewCell子视图。
  • 不要通过检查触摸点来确定单元格,它是错误没有评论..
  • 这里不要使用关联对象,非常糟糕您可以在此处阅读有关运行时反模式的文章:http://nshipster.com/associated-objects/

那我们该怎么办?我们应该遵循委托模式。缩放也是。您可以存储指向您单元格中所需数据的链接。

你的手机标题:

contentView

你的手机的实施:

@class CellWithButton;

@protocol CellWithButtonDelegate <NSObject>

- (void)cellWithButtonDidPressed:(CellWithButton *)cell;

@end

@interface CellWithButton : UITableViewCell

@property id anyData;
@property (nonatomic, weak) id <CellWithButtonDelegate> *delegate;

@end

现在你的控制器:

- (void)buttonPressed:(id)sender
{
    [self.delegate cellWithButtonDidPressed:self];
}

答案 1 :(得分:0)

你可以通过这样做获得全细胞

   a b  c  d  e
1 NA 0 NA 20  0

然后你可以得到像这样的对象

UITableViewCell *cell = (UITableViewCell *)[button superView] superView];

答案 2 :(得分:0)

首先,在按钮操作中,将按钮的点转换为tableview的indexPath,然后你可以使用该indexPath从数据数组甚至单元格中获取值

    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
       //Do stuff with the data array
       //Object *obj = [dataArray objectAtIndex:indexPath.row]
       //Get the text from the array

       //OR

       //YourCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];    
       //NSString *labelString = cell.textLabel.text;
    }

答案 3 :(得分:0)

不要在tablviewcell.m文件中创建目标方法。只需创建一个按钮的插座,然后在创建表的基础控制器中添加目标,并按照描述的流程进行操作。
在你的cellForRowAtIndexPath:方法中给按钮一个带有indexPath.row的标签,在按钮的动作方法中只需获取标签并调用cellForRowAtIndexPath来获取cell.By单元格,你可以获取所有值

 -(void)BtnOfCellTapped:(id)sender
 {
     UIButton *btn = (UIButton*)sender;
     CustomCell *cell = (CustomCell*)[tblView cellForRowAtIndexPath:btn.tag];
    NSLog(@"%@",cell.badgeValue);
 }

答案 4 :(得分:0)

您可以使用关联对象。

如何使用关联对象?

设置属性

objc_setAssociatedObject(self, @"AnyString", object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

获取财产

objc_getAssociatedObject(self,@"AnyString");

供参考:http://nshipster.com/associated-objects/