Unified UIViewController “became frontmost” detection?

前端 未结 2 558
梦如初夏
梦如初夏 2020-12-08 14:48

In my mind, these situations are all parallel:

  • My view controller presented another view controller fullscreen, which has now been dismissed

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 15:32

    What the cases have in common is not the appearance of the original view controller but the disappearance of the presented/pushed view controller. Therefore, one simple and clear solution seems to be a protocol-and-delegate architecture. Declare a pair of protocols, as follows:

    protocol Home : class {
        func comingHome()
    }
    protocol Away : class {
        var home : Home? {get set}
    }
    extension Away where Self : UIViewController {
        func notifyComingHome() {
            if self.isBeingDismissed || self.isMovingFromParent {
                self.home?.comingHome()
            }
        }
    }
    
    • The home view controller must adopt Home, and must set each view controller's home to self when it presents or pushes it.

    • The presented or pushed view controllers must adopt Away, and must implement viewWillDisappear as follows:

      override func viewWillDisappear(_ animated: Bool) {
          super.viewWillDisappear(animated)
          self.notifyComingHome()
      }
      

    This works for the four cases listed in the question. It's a pity, though, that Cocoa Touch doesn't do this for you automatically.


    EDIT This approach has become even more important in my apps now that iOS 13 has forced nonfullscreen presented view controllers upon us. Also, I have subclassed UIAlertController so that it conforms to Away.

提交回复
热议问题