我有一个光标对象,我希望能够告诉它何时与nsbutton相交,以及它是否持续3秒。我的代码工作,除了当光标靠近按钮时,它会冻结直到它已经三秒钟,然后记录“按钮重叠3秒”。
NSDate* date;
-(BOOL)checkIfIntersects :(NSButton*)button {
BOOL intersects = CGRectIntersectsRect (cursor.frame,button.frame);
if (intersects) {
date = [NSDate date];
while (intersects) {
if ([date timeIntervalSinceNow] < -1)
{
NSLog(@"Button overlapped for 3 seconds");
break;
}
intersects = CGRectIntersectsRect (cursor.frame,button.frame);
}
}
return NO;
}
答案 0 :(得分:1)
这是因为你的线程被卡在while(intersects)
循环中,只有在满足内部if
语句后退出。这会挂起你的整个帖子。
最快/最简单的解决方案是在您的功能之外加上NSDate
。
NSDate* momentIntersectionBegan = nil;
BOOL intersectedPreviously = false;
-(BOOL)checkIfIntersects :(NSButton*)button {
BOOL currentlyIntersects = CGRectIntersectsRect (cursor.frame,button.frame);
if (currentlyIntersects) {
if(intersectedPreviously){
if ([momentIntersectionBegan timeIntervalSinceNow] < -3)
{
NSLog(@"Button overlapped for 3 seconds");
}
}else{
momentIntersected = [NSDate date];
}
intersectedPreviously = true;
}else{
intersectedPreviously = false;
}
return NO;
}