Create menu dynamically but using same view controller [PagingMenuController]

后端 未结 1 319
-上瘾入骨i
-上瘾入骨i 2021-01-07 15:09

I am trying to create ButtonBar based paging menu but it will be dynamic because the data (title for no. of menu) created will come from the server. Unfortunately, there is

1条回答
  •  -上瘾入骨i
    2021-01-07 16:05

    My solution is to make a synchronous call to the server to fetch the data that i need to populate the menu. It is possible that there is an asynchronous solution but i can't quite figure it out, since my app depends on completely on the menu items.

       fileprivate func parseMenuItems() {
        self.menuItems = [MenuObject]()
        let url = URL(string: MENU_URL)
        do {
            let data = try Data(contentsOf: url!)
            let json = JSON(data: data)
            for (_, subJson) in json["items"] {
                guard let name = subJson["name"].string else {return}
                guard let url = subJson["url"].string else {return}
                let menuItem = MenuObject(name: name, url: url)
                self.menuItems.append(menuItem)
            }
        } catch {
            print(error)
        }
    }
    

    For parsing I am using SwiftyJson, but that is irrelevant here.

    This function (parseMenuItems()) is called before super.viewDidLoad().

    Next step is to populate view controllers with menuItems data:

    override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
        var children = [UIViewController]()
    
        for menuItem in menuItems! {
             let child = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TestViewController") as! TestViewController
                child.name = menuItem.name
                child.url = menuItem.url
    
                children.append(child)
            }
        }
        return children
    
    }
    

    Hope it helps :)

    0 讨论(0)
提交回复
热议问题