在iOS開發(fā)中,我曾遇到這樣一個問題,很久都未能解決,就是在cell上添加一個button,當(dāng)我們點(diǎn)擊button時,它是沒有高亮效果的,除非我們長按button,我這里整理一下解決這個問題的方法
原文鏈接: http://stackoverflow.com/questions/19256996/uibutton-not-showing-highlight-on-tap-in-ios7
解決方案一:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Button點(diǎn)擊效果測試";
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 注意,本人測試系統(tǒng)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;
}
}
// 該方式相當(dāng)于上面兩個循環(huán)的合集,并且實現(xiàn)方式更加優(yōu)雅,推薦使用它,而不是使用上面兩個循環(huán)
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; }];
}
該方案比較簡單粗暴,我們創(chuàng)建一個UIButton的分類,然后將它導(dǎo)入pch文件中,就徹底解決了button的點(diǎn)擊效果問題,比起方案一要簡單一些