实例化一次UIView并在所有ViewController中重复使用

问题描述 投票:0回答:1

我正在创建一个音乐播放器应用,并且我有一个播放/暂停栏来控制音乐。

我希望能够在不同的VC:s中在我的应用程序中使用此栏,但是如果不重新启动每个VC中的“播放/暂停视图”,就无法弄清楚如何做到这一点。如果我重新启动它,则暂停和播放按钮的状态不会在VC:s之间传递。我目前在每个VC中创建一个容器视图,并将其分配给名为“ PlayBar.swift”的播放/暂停栏类。

enter image description here

这是我当前使用xib播放/暂停的代码:

    class PlayBar: UIView {

    let kCONTENT_XIB_NAME = "PlayBarView"
    @IBOutlet weak var playBtnOutlet: UIButton!
    @IBOutlet weak var premiumBtnOutlet: UIButton!
    @IBOutlet weak var timerBtnOutlet: UIButton!
    @IBOutlet var playBarView: UIView!
    static var currentWindow = UIViewController()
    static var currentlyPlaying = false

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()

    }

    func commonInit() {
        Bundle.main.loadNibNamed(kCONTENT_XIB_NAME, owner: self, options: nil)
        playBarView.fixInView(self)
    }

    @objc func playBtnAction(sender: UIButton){

    }
}

extension UIView
{
    func fixInView(_ container: UIView!) -> Void{
        self.translatesAutoresizingMaskIntoConstraints = false;
        self.frame = container.frame;
        container.addSubview(self);
        NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: container, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
        NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: container, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
        NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: container, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
        NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: container, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
    }
}
ios swift uiview storyboard xib
1个回答
0
投票

如果我重新启动它,则暂停和播放按钮的状态不会在VC之间通信:

请传达。它不会自己发生。将状态信息从一个vc传递到另一个vc,或将其保存在所有vc均可访问的公共位置。

我目前在每个VC中创建一个容器视图,并将其分配给名为“ PlayBar.swift”的播放/暂停栏类。

没错,但是如果您的目标是只有一个播放器栏,那么您的体系结构将倒退。播放器栏上只有一个播放器vc,并且包含所有其他vc。

我给出了两种相反的可能性,因为不清楚您的目标是什么。

© www.soinside.com 2019 - 2024. All rights reserved.