最近做项目老大说要把所有可以点到的按钮加上触摸反馈,但是遇到一个问题,就是我的cell上添加一个button,当我点button时,fuck竟然没有高亮效果的,除非我长按 button。这就尴尬了,被说是按钮的反馈不统一,要受罚。。。。
解决方案:
self.tableView.delaysContentTouches = NO;
for (id obj in self.tableView.subviews) {
if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]) {
[obj setDelaysContentTouches:NO];
}
}
在其他地方看到一些其他的解决方案,代码如下,原文链接在文章的结尾
方案一:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Button点击效果测试";
self.tableView.delaysContentTouches = NO;
// iOS7
for (id view in self.tableView.subviews)
{
if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewWrapperView"])
{
if([view isKindOfClass:[UIScrollView class]])
{
UIScrollView *scroll = (UIScrollView *) view;
scroll.delaysContentTouches = NO;
}
break;
}
}
// iOS8 注意,本人测试系统iOS10,没有走这个方法,走上面那个方法
for (id view in self.tableView.subviews)
{
if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewCellScrollView"])
{
if([view isKindOfClass:[UIScrollView class]])
{
UIScrollView *scroll = (UIScrollView *) view;
scroll.delaysContentTouches = NO;
}
break;
}
}
// 该方式相当于上面两个循环的合集,并且实现方式更加优雅,推荐使用它,而不是使用上面两个循环
for (id obj in self.tableView.subviews) {
if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]) {
[obj setDelaysContentTouches:NO];
}
}
}
方案二:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
[NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = YES;}];
}
-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesCancelled:touches withEvent:event];
[self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
[self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}
- (void)setDefault
{
[NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = NO; }];
}
-
方案二的博主原话说:该方案比较简单粗暴,我们创建一个UIButton的分类,然后将它导入pch文件中,就彻底解决了button的点击效果问题,比起方案一要简单一些
参考文章: https://juejin.im/entry/580f4f33570c350068fea175
原文链接: http://www.jianshu.com/p/b909f8f3ca6c
参考资料: https://stackoverflow.com/questions/19256996/uibutton-not-showing-highlight-on-tap-in-ios7