Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PageMenu how to add view controllers dynamically (programmatically)?

Tags:

ios

swift

I want my app to look like the image below.

I am using PageMenu to acomplish this result. The data is fetcehd from a web API. I want to dynamically create view controllers based on the number of days that the web API responds with so that each day can have a view controller so that it can display schedule for that day. How can I accomplish this?

enter image description here

like image 219
Ali Mir Avatar asked Jan 29 '26 01:01

Ali Mir


2 Answers

reading from the link you provided yourself it has:

// Array to keep track of controllers in page menu
var controllerArray : [UIViewController] = []

// Create variables for all view controllers you want to put in the 
// page menu, initialize them, and add each to the controller array. 
// (Can be any UIViewController subclass)
// Make sure the title property of all view controllers is set
// Example:
var controller : UIViewController = UIViewController(nibName: "controllerNibName", bundle: nil)
controller.title = "SAMPLE TITLE"
controllerArray.append(controller)

So what you have to do is : have a function that returns a [dailyModel]. Your dailyModel would look something like this:

struct dailyModel {
let programStartingTime : String // 6:45
let item : [item] // [(Maghrib & Isha Prayer, 20, 0),(Ziarat-e-Ashura, 20, 1), ...otherItems...]
}

struct item{
let duration : Int? //minutes
let name : String // Maghrib and Isha prayers
let row : Int? //  0
}

Then loop through that dailyModel and using its parameters you instantiate & populate viewcontroller and then append each of them as the tutorial is doing.

This isn't the best code but I hope you get the idea.

like image 190
mfaani Avatar answered Jan 31 '26 16:01

mfaani


Simply create a loop add same controller multiple times. i created addPageMenu function. call it when you get the response.

func addPageMenu(count: Int) {

 var controllerArray : [UIViewController] = []

  for i in count {

  var controller : UIViewController = UIViewController(nibName: "controllerNibName", bundle: nil)
  if i == 0 {
  controller.title = "SUNDAY"
  } else if i == 1 {
   controller.title = "MONDAY"
  }...

  controllerArray.append(controller)

 }

  let pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 0.0, self.view.frame.width, self.view.frame.height), pageMenuOptions: parameters)

// Lastly add page menu as subview of base view controller view
// or use pageMenu controller in you view hierachy as desired
  self.view.addSubview(pageMenu!.view)
 }
like image 34
Sahil Avatar answered Jan 31 '26 14:01

Sahil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!