简体   繁体   中英

How to programmatically create a new UIViewController in Swift

I am new to the world of iOS development and Swift, and have run into a problem. When my app starts, it is to connect to a web service, and download a JSON string containing information for "posts", then, it should load the first post into the first view. After that, the user can swipe left or right to load a new view with the next post. I figured that I could use something like this to do that:

let nextView:ViewControllerName = ViewControllerName();
self.presentViewController(nextView, animated: true, completion: nil)

However, this infers that I already have another UIViewController created and ready, but since I am dynamically loading data, I will have to create new views on demand and create an indefinite number of them.

How, then, can I create a new UIViewController , add controls to it, add controls (including custom controls), and populate the controls with data all in Swift code? Could I somehow integrate it with storyboards?

You could have one UIViewController which contains a paging scroll view ( UIScrollView ) that contains the views to be displayed.

When the user swipes, you just populate the view to be displayed with the appropriate data. A common pattern is to have 3 views in the scroll view with the next and previous ones already preloaded.

  1. Trasform your JSON response into an array of UIViewControllers ( factory pattern). For each item you can create something like - (UIViewController *)viewControllerFromObject:(MyObject) object
  2. Install ISScrollViewPageSwift
  3. Integrate it

Search for "UIPageViewController" tutorials. You could also use a third party library like "iCarousel" which makes it a little bit easier.

https://github.com/nicklockwood/iCarousel

But: creating a new view dynamically on demand asynchronously over the network will create a very poor user experience. On iOS the everyone is used to a very fast and fluid user experience - as soon as the user swipes he wants to see immediately the next view. But a network request takes 0.5 seconds - 10.0 seconds, depending on you network connection. It would be better if you preload some pages to have them already in memory. And as soon as the user has viewed some of the preloaded pages you can preload more of them... and so on... indefinitely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM