Создать главный переключатель, чтобы изменить все цвета фона - PullRequest
0 голосов
/ 29 апреля 2019

Я хочу создать главный переключатель, который, когда он выключен, меняет цвет фона каждого класса контроллера представления на красный.Я не знаю, можете ли вы создать функцию для вызова класса, который содержит переключатель.Переключатель будет в другом классе, но фон также может быть изменен на красный при необходимости.


    import UIKit
    class Switch: UIViewController {
    var toggle = UISwitch()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(toggle)
        //set frame and other properties...

        toggle.addTarget(self, action: #selector(toggleWasToggled(_:)), for: .allEvents)
          toggle.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate ([

            toggle.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :175),
            toggle.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 100),
            toggle.widthAnchor.constraint(equalToConstant: 350),
            toggle.heightAnchor.constraint(equalToConstant: 180),
            ])
    }

    @objc func toggleWasToggled(_ sender: UISwitch) {
        //Whenever the switch is toggled you can post a notification. You can even post two seperate notifications, one for when the toggle is on, and one for when it is off.
        NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "ColorChange"), object: nil, userInfo: nil))

    }
    @objc func colorWasChanged(_ sender: Any) {
        view.backgroundColor = UIColor.blue
        print("espn")
    }
    }

    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //Add an observer in all your viewControllers that need to be notified of the color change.
        NotificationCenter.default.addObserver(self, selector: #selector(colorWasChanged(_:)), name: Notification.Name(rawValue: "ColorChange"), object: nil)
    }


    @objc func colorWasChanged(_ sender: Any) {
    view.backgroundColor = UIColor.blue
        print("cnn")
    }
    }

Ответы [ 2 ]

0 голосов
/ 30 апреля 2019

Создайте класс BaseViewController, добавьте наблюдателя и измените цвет в этом viewcontroller.

class BaseViewController: UIViewController {

    static var switchStatus = false

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(colorChanged(_:)), name: Notification.Name(rawValue: "ColorChanged"), object: nil)
    }
    @objc func colorChanged(_ notification: Notification) {
        if let switchStatus = notification.userInfo?["switchStatus"] as? Bool {
            BaseViewController.switchStatus = switchStatus
            if switchStatus {
                self.view.backgroundColor = .red
            } else {
                self.view.backgroundColor = .white
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if BaseViewController.switchStatus {
            self.view.backgroundColor = .red
        } else {
            self.view.backgroundColor = .white
        }
    }
}

Для всех остальных контроллеров представления наследуются от этого viewcontroller.Не нужно добавлять наблюдателя в каждом классе.Поскольку он унаследован от BaseViewController, он автоматически добавляет наблюдателя для изменения цвета.

class ViewController: BaseViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Теперь, когда вы изменяете значение в UISwitch, публикуйте уведомление со статусом UISwitch.Класс Switch также наследуется от BaseViewController.

class Switch: BaseViewController {
    var toggle = UISwitch()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(toggle)
        //set frame and other properties...
        toggle.addTarget(self, action: #selector(toggleWasToggled(_:)), for: .allEvents)
    }
    @objc func toggleWasToggled(_ sender: UISwitch) {
        let userInfo = ["switchStatus":sender.isOn]
        NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "ColorChanged"), object: nil, userInfo: userInfo))
    }
}
0 голосов
/ 29 апреля 2019

Вы можете использовать уведомления для чего-то вроде этого.Вот пример:

Swift 5.0

class Switch: UIViewController {
    var toggle = UISwitch()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(toggle)
        //set frame and other properties...

        toggle.addTarget(self, action: #selector(toggleWasToggled(_:)), for: .allEvents)
    }

    @objc func toggleWasToggled(_ sender: UISwitch) {
        //Whenever the switch is toggled you can post a notification. You can even post two seperate notifications, one for when the toggle is on, and one for when it is off.
        NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "ColorChange"), object: nil, userInfo: nil))
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //Add an observer in all your viewControllers that need to be notified of the color change.
        NotificationCenter.default.addObserver(self, selector: #selector(colorWasChanged(_:)), name: Notification.Name(rawValue: "ColorChange"), object: nil)
    }

    //its important to also remove the observer when the viewController is no longer being displayed
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    @objc func colorWasChanged(_ sender: Any) {
        //Change color to red here
    }
}
...