Динамически назначить ViewController для навигации - PullRequest
2 голосов
/ 21 января 2020

В моем случае у меня есть UITableView и кнопка Просмотреть все для отображения списка всех элементов на отдельных экранах. Поэтому я добавил цель для UIButton метода действия в cellForRowAt. Теперь, что я делаю в методе действия:

@IBAction func btnViewAllOffer(_ sender: UIButton) {
        let buttonPosition = sender.convert(CGPoint.zero, to: self.tblOfferView)
        let indexPath = self.tblOfferView.indexPathForRow(at: buttonPosition)

        if indexPath != nil {

            if let type = self.homeData[indexPath!.section].type {
                if type == HomeDataType.SponserProduct.rawValue {
                    let vc1 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController1") as! ViewController1
                    if let title = self.homeData[indexPath!.section].title {
                        vc1.title = title
                    }
                    self.navigationController?.pushViewController(vc1, animated: true)
                } else if type == HomeDataType.Offer.rawValue {
                    let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2") as! ViewController2
                    if let title = self.homeData[indexPath!.section].title {
                        vc2.title = title
                    }
                    self.navigationController?.pushViewController(vc2, animated: true)
                } else if type == HomeDataType.BestSeller.rawValue {
                    let vc3 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController3") as! ViewController3
                    if let title = self.homeData[indexPath!.section].title {
                        vc3.title = title
                    }
                    self.navigationController?.pushViewController(vc3, animated: true)
                }
            }
        }
    }

Что мне нужно, есть ли способ, которым я могу минимизировать код и динамически назначать view-контроллеры, поэтому нет необходимости создавать экземпляры каждого контроллера представления и pu sh их каждый раз? Что-то вроде:

var vc = UIViewController()
if let type = self.homeData[indexPath!.section].type {
    if type == HomeDataType.SponserProduct.rawValue {
        vc = ViewController1()
    }
    else if type == HomeDataType.Offer.rawValue {
        vc = ViewController2()
    } else if type == HomeDataType.BestSeller.rawValue {
        vc = ViewController3()
    }
}
self.navigationController?.pushViewController(vc, animated: true)

Ответы [ 3 ]

1 голос
/ 21 января 2020

Используйте protocol (SimilarViewController) для определения общих свойств, таких как title:

protocol SimilarViewController {
    var title: String? { get set }
}

class ViewController1: UIViewController, SimilarViewController {
    var title: String?
}
class ViewController2: UIViewController, SimilarViewController {
    var title: String?
}
class ViewController3: UIViewController, SimilarViewController {
    var title: String?
}


@IBAction func btnViewAllOffer(_ sender: UIButton) {
        let buttonPosition = sender.convert(CGPoint.zero, to: self.tblOfferView)
        let indexPath = self.tblOfferView.indexPathForRow(at: buttonPosition)

        if indexPath != nil {

            if let type = self.homeData[indexPath!.section].type {
                var vcGeneric: SimilarViewController?

                if type == HomeDataType.SponserProduct.rawValue {
                    vcGeneric = self.storyboard?.instantiateViewController(withIdentifier: "ViewController1") as! ViewController1
                } else if type == HomeDataType.Offer.rawValue {
                    vcGeneric = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2") as! ViewController2
                } else if type == HomeDataType.BestSeller.rawValue {
                    vcGeneric = self.storyboard?.instantiateViewController(withIdentifier: "ViewController3") as! ViewController3
                }


                if let title = self.homeData[indexPath!.section].title {
                    vcGeneric?.title = title
                }

                if let vcGeneric = vcGeneric  as? UIViewController {
                    self.navigationController?.pushViewController(vcGeneric, animated: true)
                }
            }
        }
}
0 голосов
/ 21 января 2020

Создайте BaseViewController и извлеките другой ViewController из BaseViewController

class BaseViewController: UIViewController {
    var viewTitle = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

    }

    func pushVC(_ vcName : String) {
        let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)

        self.navigationController?.pushViewController(vc, animated: true)
    }
}

И используйте приведенный ниже код на ViewController, который вам нужен, например:

@IBAction func btnViewAllOffer(_ sender: UIButton) {
        let buttonPosition = sender.convert(CGPoint.zero, to: self.tblOfferView)
        let indexPath = self.tblOfferView.indexPathForRow(at: buttonPosition)

        if indexPath != nil {

            if let type = self.homeData[indexPath!.section].type {
                self.viewTitle = self.homeData[indexPath!.section].title
                if type == HomeDataType.SponserProduct.rawValue {
                    self.pushVC("ViewController1")
                } else if type == HomeDataType.Offer.rawValue {
                    self.pushVC("ViewController2")
                } else if type == HomeDataType.BestSeller.rawValue {
                    self.pushVC("ViewController3")
                }
            }
        }
    }
0 голосов
/ 21 января 2020

1: создать структуру и присвоить ей значение.

    struct TitleDetails { 
         static var title : String = ""
    }

2: создайте расширение viewController и используйте его, чтобы избежать повторения кода.

    extension UIViewController {

        func pushVC(_ vcName : String) {
            let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: vcname)
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }

3: теперь вы можете вызывать его напрямую как

TitleDetails.title = yourTitleValue
self.pushVC("ViewController1")

и в вашем методе ViewDidLoad () вашего конечного контроллера представления,

self.title = TitleDetails.title
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...