UITableView cell中按钮点击无高亮效果问题解决
在工程中使用了大量的继承UIControl类,自定义了一个MyAddButton,如下设置背景高亮时显示不同颜色,以此曲风高亮显示的情况。
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backImageView.backgroundColor = [UIColor colorWithHexString:@"d9d9d9"];
} else {
self.backImageView.backgroundColor = [UIColor clearColor];
}
}
仔细检查了代码,没有问题。
出现了在TableView的cell上放置该按钮MyAddButton。出现了点击高亮无效果的问题。
仔细处理后发现UIScrollView中的delaysContentTouches属性
UIScrollView中有一个属性叫delaysContentTouches,官方文档对它的解释是:
If the value of this property is YES, the scroll view delays handling the touch-down gesture until it can determine if scrolling is the intent. If the value is NO , the scroll view immediately calls touchesShouldBegin:withEvent:inContentView:. The default value is YES.
意思就是设置为NO。就不会存在那个150ms的判断时间了,直接执行后续操作。那么咱们设置为NO来试试呗。结果确实如所想那样,UIButton立即响应并高亮。
基于这个属性,所以创建了一个BaseTableView类。
代码如下
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
self = [super initWithFrame:frame style:style];
if (self)
{
self.delaysContentTouches = NO;
// iterate over all the UITableView's subviews
for (id view in self.subviews)
{
// looking for a UITableViewWrapperView
if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewWrapperView"])
{
// this test is necessary for safety and because a "UITableViewWrapperView" is NOT a UIScrollView in iOS7
if([view isKindOfClass:[UIScrollView class]])
{
// turn OFF delaysContentTouches in the hidden subview
UIScrollView *scroll = (UIScrollView *) view;
scroll.delaysContentTouches = NO;
}
break;
}
}
if (IS_IOS11_OR_LATER) {
self.estimatedRowHeight = 0;
self.estimatedSectionHeaderHeight = 0;
self.estimatedSectionFooterHeight = 0;
}
}
return self;
}
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
if ([view isKindOfClass:[UIButton class]])
{
return YES;
}
if ([view isKindOfClass:[UIView class]])
{
return YES;
}
return [super touchesShouldCancelInContentView:view];
}
更改后,MyAddButton,出现了高亮效果。
本文为学习的记录,以便之后查阅。谢谢。