检查布尔值是否为真 x 秒 - Swift

Checking if a bool is true for x seconds - Swift

我正在使用 VNDetectRectanglesRequest,我想检查我检测到的矩形的 CGRect 是否在另一个 CGRect 内1 秒。到目前为止,这是我的代码:

let x = self.view.frame.width * detectedRectangle.boundingBox.origin.x
let height = self.view.frame.height * detectedRectangle.boundingBox.height
let y = self.view.frame.height * (1 - detectedRectangle.boundingBox.origin.y) - height
let width = self.view.frame.width * detectedRectangle.boundingBox.width
let rectangleDetected = CGRect(x: x, y: y, width: width, height: height)

self.redView.frame = rectangleDetected

let outsideGuideRect = CGRect(x: self.boardMargin*1/2, y: (self.view.frame.height-self.view.frame.width+1/2*self.boardMargin)/2, width: self.view.frame.width-1/2*self.boardMargin, height: self.view.frame.width-1/2*self.boardMargin)
print(outsideGuideRect.contains(rectangleDetected))
if outsideGuideRect.contains(sudokuBoardRect) {

    // HERE I WANT TO CHECK IF THIS IF STATEMENT IS TRUE FOR 1 second

}

以上代码在一个函数中,每帧 运行。我如何检查 if 语句是否为真一秒钟?谢谢!

我从你的问题中了解到,"you want to perform an action after 1 sec once your rect B come inside rect A (without leaving)"。

以下可能是我从头脑中得出的一个可能的解决方案,如果我们多想想,可能会有更好的解决方案。

//initialize _insideRect as false globally
if outsideGuideRect.contains(sudokuBoardRect) {
    // HERE I WANT TO CHECK IF THIS IF STATEMENT IS TRUE FOR 1 second
    if (!_insideRect) {
      _insideRect = true;
      DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
        if (_insideRect) {
          // your function here
        }
      }
    }
}else{
    _insideRect = false;
}