我正在设置一个简单的tvOS应用程序,底部有一个菜单坞(包含按钮的堆栈视图)。在5秒不活动后,我希望停靠隐藏(向下移动,移出视图)并从当前聚焦按钮中移除焦点。码头应重新出现,并重新集中于遥控活动。使用以下代码,dock将隐藏,但仅在应用程序启动后隐藏一次。任何帮助都将不胜感激!

@IBOutlet weak var menuDock: UIStackView!

var timer = Timer()

func resetTimer() {
    timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.showDock))
    self.view.addGestureRecognizer(tapRecognizer)
}

@objc func hideDock() {
    UIView.animate(withDuration: 0.5, animations: {
        self.menuDock.frame.origin.y += 240
    }, completion: nil)
    timer.invalidate()
}

@objc func showDock() {
    UIView.animate(withDuration: 0.5, animations: {
        self.menuDock.frame.origin.y -= 240
    }, completion: nil)
    timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
    timer.invalidate()
}

最佳答案

@IBOutlet weak var menuDock: UIStackView!

var timer = Timer()

func resetTimer() {
    timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.showDock))
    self.view.addGestureRecognizer(tapRecognizer)
  }

  @objc func hideDock() {
    UIView.animate(withDuration: 0.5, animations: {
      self.menuDock.frame.origin.y += 240
      self.menuDock.arrangedSubviews.forEach{
        ($0 as? UIButton)?.isEnabled = false
      }
      self.setNeedsFocusUpdate()
      self.updateFocusIfNeeded()
    }, completion: nil)
    timer.invalidate()
  }

  @objc func showDock() {
    UIView.animate(withDuration: 0.5, animations: {
      self.menuDock.frame.origin.y -= 240
      self.menuDock.arrangedSubviews.forEach{
        ($0 as? UIButton)?.isEnabled = true
      }
      self.setNeedsFocusUpdate()
      self.updateFocusIfNeeded()
    }, completion: nil)
    timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
    timer.invalidate()
  }

关于swift - 计时器到期后如何从UIButton移除焦点(tvOS),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58100776/

10-09 16:27