在使用 swift 的 iOS 中,如何创建一个可拖动且浮动的 UIView,该 UIView 始终位于整个应用程序的顶部

In iOS using swift, how do I create a draggable and floating UIView that is always on the top of throughout the entire app

提问人:Akbar Khan 提问时间:1/9/2019 最后编辑:Akbar Khan 更新时间:1/9/2019 访问量:2183

问:

  • 我想让 UIView 始终位于顶部(而不是 ViewController)在整个应用程序中,就像 youtube 播放器一样???
  • 我想让这个UIView可拖动到屏幕上吗?enter image description here
iOS iPhone Swift UIVIEW、UIViewController

评论

0赞 Muhammad Shauket 1/9/2019
您可以保留在导航控制器中...或者以这样一种方式设计您的应用程序,每当 ViewController 打开它时,它都必须具有俯视图
0赞 Akbar Khan 1/9/2019
再详细说明你的答案。@ShauketSheikh
0赞 Kuldeep 1/9/2019
参考这个 : stackoverflow.com/questions/38540091/...
0赞 Muhammad Shauket 1/9/2019
创建一个基本控制器并随每个控制器继承该控制器,在基本控制器中,在顶部添加一个类似标题的视图

答:

0赞 Parth Dhorda 1/9/2019 #1

您可以使用以下代码向应用程序窗口添加视图

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // Do any additional setup after loading the view, typically from a nib.
    let newView = UIView()
    newView.frame = CGRect(x:0,y:UIApplication.shared.statusBarFrame.height, width: view.frame.size.width, height: 30)
    newView.backgroundColor = UIColor.red
    let label = UILabel()
    label.frame = newView.bounds
    label.text = "header"
    newView.addSubview(label)
    UIApplication.shared.keyWindow?.addSubview(newView)

    let bounds = self.navigationController!.navigationBar.bounds
    self.navigationController?.navigationBar.frame = CGRect(x: 0, y: newView.frame.size.height + newView.frame.origin.y, width: bounds.width, height: bounds.height  )
}

请检查并让我知道这是否有效

评论

0赞 Akbar Khan 1/9/2019
这奏效了,但有一个问题,当我关闭视图控制器和导航控制器时,一切都停止了。这意味着我丢失了视图控制器的所有引用。
0赞 Parth Dhorda 1/9/2019
尝试使用 AppDelegate 中的单个导航控制器
0赞 Arjun Patel 1/9/2019 #2

UIApplication.shared.keyWindow?。addSubview(UIView)