近來做項目時發現一個現象:放在 UIScrollView 上的 UIButton,點擊時沒有立即出現高亮狀態,但其實點擊事件確實已經觸發了。這會給用戶一種「按鈕沒被點中」的錯覺。而如果長按一段時間,按鈕才會高亮。由此可以推斷,這是時間長短造成的差異。
順著這個思路追查下去,問題指向了 UIScrollView 的 delaysContentTouches 屬性。
蘋果官方文檔對此屬性的解釋是:默認值為 YES。若設為 NO,系統會立即調用 -touchesShouldBegin:withEvent:inContentView:。
也就是說,delaysContentTouches 默認為 YES 時,UIScrollView 會在收到手勢後延遲約 150ms,用來判斷該手勢是否要觸發滾動;若設為 NO,則會立刻把手勢分發給子視圖。
不過,僅僅把它設為 NO 並不足夠,因為這樣會導致當你手指按在帶手勢識別的視圖上時無法拖動 ScrollView。因此我們還需要重載 touchesShouldCancelInContentView: 方法,它決定手勢是否取消傳遞給 View:返回 NO 時手勢留在 ScrollView 上,返回 YES 時則傳給 View。
方案就很明確了:把 UIButton 所有屬於 UIScrollView 的父視圖的 delaysContentTouches 設為 NO,並重寫 touchesShouldCancelInContentView: 方法即可。
- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { self.delaysContentTouches = NO; } return self; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.delaysContentTouches = NO; } return self; } - (BOOL)touchesShouldCancelInContentView:(UIView *)view { if ([view isKindOfClass:[UIButton class]]) { return YES; } return [super touchesShouldCancelInContentView:view]; }
相比 UIScrollView,UITableView 的視圖結構更為複雜。它在 iOS7 與 iOS8 中的結構並不相同,而且存在一些我們平時編碼時永遠接觸不到的私有視圖,需要透過 Debug 逐一找出 subviews。
在 iOS7 中,UITableView 內部存在 n+1 個 UIScrollView:一個是 UITableView 本身,另外 n 個則分佈於 cell 與其 contentView 之間,類名為 UITableViewCellScrollView(此類在 iOS8 已移除)。
在 iOS8 中,UITableView 內含 2 個 UIScrollView:一個是 UITableView 本身,另一個位於 UITableView 與 UITableViewCell 之間,類名為 UITableViewWrapperView。值得注意的是,UITableViewWrapperView 在 iOS7 中並不是一個 UIScrollView。
理解之後,直接看代碼:
@implementation ResponseTableView - (instancetype) initWithCoder : (NSCoder *) aDecoder { self = [super initWithCoder:aDecoder]; if (self) { self.delaysContentTouches = NO; //因為 UITableViewWrapperView 在iOS7不屬於UIScrollView //iOS7 for (id obj in self.subviews) { if ([NSStringFromClass([obj class]) isEqualToString:@"UITableViewCellScrollView"]) { UIScrollView *scrollView = (UIScrollView *) obj; scrollView.delaysContentTouches = NO; break; } } //ios 8 for (id view in self.subviews) { if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewWrapperView"]) { if ([view isKindOfClass:[UIScrollView class]]) { UIScrollView *scrollView = (UIScrollView *) view; scrollView.delaysContentTouches = NO; } break; } } } return self; } - (BOOL) touchesShouldCancelInContentView : (UIView *) view { if ([view isKindOfClass:[UIButton class]]) { return YES; } return [super touchesShouldCancelInContentView:view]; }
以上方法,就能徹底解決 Button 延遲高亮的問題。