我创建了一个自定义表格视图单元格,其上有一个按钮,并在同一个文件tableviewcell.m(基本calsee UITableViewCell)中的按钮targetof。如何从发件人的选项中获得值选项
当我点击按钮然后行动被调用。
我要做的是从该按钮的发件人选项中获取值。如图所示想要获取“badgename”的值。
我创建了一个自定义表格视图单元格,其上有一个按钮,并在同一个文件tableviewcell.m(基本calsee UITableViewCell)中的按钮targetof。如何从发件人的选项中获得值选项
当我点击按钮然后行动被调用。
我要做的是从该按钮的发件人选项中获取值。如图所示想要获取“badgename”的值。
你可以这样做
UITableViewCell *cell = (UITableViewCell *)[button superView] superView];
那么你可以得到你的对象是这样
UILabel *label = (UILabel *)[cell viewWithTag:1234];
请不要这样做。 –
是否有任何问题...请告诉我,以便我可以更新自己。 –
看看我的答案,我会扩展它。 –
首先,在按钮动作得到全细胞,转换点按钮到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;
}
Donot在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);
}
你认为会发生什么,如果表有更多的一个部分 – sage444
你应该当你想要的所有值跟踪来自单元格的一些其他事件,而不仅仅是默认选择。例如你添加一些按钮。
UIView
的tag
属性是坏! 用标签阅读代码并不容易。当你不仅有行而且还有段时,你会做什么?UITableViewCell
作为 superview
您的按钮是不好太! 按钮可以直接添加为UITableViewCell
子视图或作为单元的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];
}
现在你的控制器:
- (UITableViewCell *)tableView cellFor...
{
CellWithButton *cell = ...;
cell.anyData = myData;
cell.delegate = self;
}
- (void)cellWithButtonDidPressed:(CellWithButton *)cell
{
id myData = cell.anyData;
// Wow! Now you have your data.
// And you can even find `indexPath` for your cell
// by calling [self.tableView indexPathForCell:cell].
}
您可以使用关联的对象这一点。
如何使用关联的对象?
要设置属性
objc_setAssociatedObject(self, @"AnyString", object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
要获取属性
objc_getAssociatedObject(self,@"AnyString");
你有没有读过反模式部分? –
ü希望的是得到的值标签在包含该按钮的单元格中,我是否正确? – Tj3n
是的,我想获得标签名称“badgesname”的价值 –
哦,我的..分开存储所有东西。你应该做的是休闲委派模式,并将数据保存在单元格中。然后,当按下按钮时,可以使用self(从单元格)和单元格外部调用委托方法,以获取单元格的数据。 –