iOS——關於Cell上Button點選效果
阿新 • • 發佈:2019-02-04
- (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的點選效果問題,比起方案一要簡單一些