iOS 中,经常要实现UITableVIewCell 点击埋点,这里通过自动化埋点的方式进行实现。
思路:通过运行时hook tableViewCell的 setSelected:animated:方法,
在交换的方法中实现埋点逻辑,并调用原来的实现
cell分类
@property (nonatomic, strong) NSString *actionName;
- (void)setMonitorSelected:(BOOL)selected;
#import <objc/runtime.h>
static const void *monitorCellActionNameKey = "monitorCellActionNameKey";
@implementation UITableViewCell (AT)
@dynamic actionName;
+ (void)load
{
instanceMethod_fastExchangeImplementations([self class], @selector(setSelected:animated:), [self class], @selector(setSelectedWithFilter:animated:));
}
-(void)setSelectedWithFilter:(BOOL)selected animated:(BOOL)animated
{
if (selected && !self.skipTrack) {
UIView *tempSuperView = self.superview;
while (tempSuperView) {
if ([tempSuperView isKindOfClass:[UITableView class]]) {
break;
}
tempSuperView = tempSuperView.superview;
}
// 非LBScrllView的cell,才由setSelected触发点击采集,LB cell由didSelected触发,
if (tempSuperView && [tempSuperView isKindOfClass:[UITableView class]]
&& ![tempSuperView isKindOfClass:[LBTableView class]] && ![tempSuperView isKindOfClass:[LBScrollView class]]) {
UITableView *tableView = (UITableView *)tempSuperView;
if (![tableView isDragging] && ![tableView isTracking] && ![tableView isDecelerating]) {
[self setMonitorSelected:selected animated:animated];
}
}
}
[self setSelectedWithFilter:selected animated:animated];
}
- (void)setMonitorSelected:(BOOL)selected
{
[self setMonitorSelected:selected animated:NO];
}
-(void)setMonitorSelected:(BOOL)selected animated:(BOOL)animated
{
if (selected && !self.skipTrack) {
//埋点操作
}
}
- (NSString *)actionName {
return objc_getAssociatedObject(self, monitorCellActionNameKey);
}
- (void)setActionName:(NSString *)monitorActionName{
objc_setAssociatedObject(self, monitorCellActionNameKey,
monitorActionName,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end