我有自定义单元格在由自定义类(.h和.m文件)定义的UITableView中。我能够显示单元格,并更改列表中每个单元格的文本,但是我的自定义单元格中也有按钮(实际上是两个)。当我点击按钮时,我需要知道哪个行的按钮已被点击。有没有什么办法可以在自定义的ui单元类中得到它?每行的按钮UITableView
我希望我的要求很明确。如果没有,请随时发表评论,我会尽力解释。
我有自定义单元格在由自定义类(.h和.m文件)定义的UITableView中。我能够显示单元格,并更改列表中每个单元格的文本,但是我的自定义单元格中也有按钮(实际上是两个)。当我点击按钮时,我需要知道哪个行的按钮已被点击。有没有什么办法可以在自定义的ui单元类中得到它?每行的按钮UITableView
我希望我的要求很明确。如果没有,请随时发表评论,我会尽力解释。
您可以使用此方法:
与每个按钮关联的对象值。
@implementation UIButton (AssociatedObject)
-(void)setAssociatedObject:(id)object
{
objc_setAssociatedObject(self, @"_associatedObject", object, OBJC_ASSOCIATION_RETAIN_NONATOMIC) ;
}
-(id)associatedObject
{
return objc_getAssociatedObject(self, @"_associatedObject") ;
}
@end
使用此类似这样的:你可以通过添加一个类别的UIButton
@interface UIButton (AssociatedObject)
@property (nonatomic, retain) id associatedObject ;
@end
实现支持此
myButton.associatedObject = <some object>
设置动作/目标到您的视图控制器(或可能桌子代表)
[ myButton addTarget:<view controller> action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside ] ;
在您的操作中,查看发件人的关联对象。发件人将是你的UIButton
-(void)buttonTapped:(UIButton*)sender
{
// retrieve object associated with the tapped button:
id associatedObject = sender.associatedObject ;
}
你不显示任何代码发表评论,但总体来讲,您可以:
定义每个代表表行按钮tag
按钮出现在哪里;
当你的按钮操作方法被调用时,你可以访问按钮的属性tag
来知道它是哪一行。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
...
}
...
[button setTag:indexPath.row];
...
}
- (void)buttonPressedAction:(id)sender
{
UIButton *button = (UIButton *)sender;
int row = button.tag;
}
更详尽的解决方案,看看this S.O. thread。
我已经通过为自定义单元类创建并且然后使UIViewController
为每个自定义单元处理UITableView
delegate
来完成此操作。
然后接上了UIButton
到IBAction
在打了一个电话给它的委托有关它或信息,我需要地作用于细胞信息的自定义单元格类。
所以我会成立一个的东西,如:
@protocol CustomCellDelegate <NSObject>
- (void) cellButtonPressed:(NSDictionary *)stuffForDelegate;
@end
然后当我在ViewController
实施cellButtonPressed:
我会用stuffForDelegate
,以确定哪些细胞是还是什么信息,我需要采取行动。
tag
方法没问题,但是我觉得处理所有标签飞行的问题非常繁琐,我更喜欢使用对象和协议以及代表。
+1为您的按钮指定一个标签是要走的路。 – Stunner 2012-07-25 21:16:05
谢谢,会尽力回复你。 :) – Kgrover 2012-07-25 21:34:12
如果用户可以在不重新加载数据的情况下在表中插入/删除/重新排序行,则此解决方案将不起作用。 – Argentumko 2012-11-06 08:29:55