How to make UIPageViewController switch controllers automatically - ios

I was following this great tutorial from Duc Tran about UIPageViewController. I was wondering how would you make the controllers inside your UIPageViewController transition automatically without having the user swipe. This is how the code looks without the delegate and datasource.
class AnimesPageVC: UIPageViewController {
override var navigationOrientation: UIPageViewControllerNavigationOrientation {return .horizontal}
weak var pageViewControllerDelegate: AnimePagesVCDelegate?
var timeInterval: Int?
var images: [UIImage]?
lazy var animes: [UIViewController] = {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var animes = [UIViewController]()
if let images = self.images {
for image in images {
let anime = storyboard.instantiateViewController(withIdentifier: "AnimeImage")
animes.append(anime)
}
}
self.pageViewControllerDelegate?.setUpPageController(numberOfPages: animes.count)
return animes
}()
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
dataSource = self
loadPage(atIndex: 0)
}
func loadPage(atIndex: Int) {
let anime = animes[atIndex]
var direction = UIPageViewControllerNavigationDirection.forward
if let currentAnime = viewControllers?.first {
if let currentIndex = animes.index(of: currentAnime) {
if currentIndex > atIndex {
direction = .reverse
}
}
}
configurePages(viewController: anime)
setViewControllers([anime], direction: direction, animated: true, completion: nil)
}
func configurePages(viewController: UIViewController) {
for (index, animeVC) in animes.enumerated() {
if viewController === animeVC {
if let anime = viewController as? AnimeVC {
anime.image = self.images?[index]
self.pageViewControllerDelegate?.turnPageController(to: index)
}
}
}
}
}
So how would I be able to get that kind of behavior. Would appreciate any help. :)

Add a timer to your view did load and call the same load function with updated index
Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { (_) in
// call your function here
self.loadPage(atIndex: index + 1)
// you have to update your index also.
self.index = self.index + 1
}
This will call your loadPage function each 0.3 sec
keep in mind that my solution is only for one way if you it's only going to next page because I am adding to automatically it will not come back to previous controller for that you have do something like
index = index - 1

Related

Dynamically assign ViewController to Navigate

In my case I have UITableView and have View all button for the listing of all the items in separate screens. So I added target for UIButton action method in cellForRowAt. Now what I am doing in action method:
#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)
}
}
}
}
What I need, is there any way I can minimize the code and assign viewcontrollers dynamically so there is no need to instantiate each view controller and push them everytime?
Something like:
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)
Use a protocol (SimilarViewController) to define the common properties like 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)
}
}
}
}
1: create a struct and assign the value to it.
struct TitleDetails {
static var title : String = ""
}
2: create an extension of viewController and use it to avoid code repetition.
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: now you can call it directly as,
TitleDetails.title = yourTitleValue
self.pushVC("ViewController1")
and in your ViewDidLoad() method of your destination view controller,
self.title = TitleDetails.title
Create BaseViewController and derived other ViewController from 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)
}
}
And use below code on ViewController you need like:
#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")
}
}
}
}

Delegate stops being called swift

I have a delegate which I use to trigger next page of a Pageview controller and I have 6 viewcontrollers attached to the page viewcontroller. after the first 3 calls in 3 different controllers, the delegate stops getting called and as such, the next page of the page controller is not triggered, beleow is my code which works for first 3 and stops getting called after the first 3
This Button tap code is in 5 of the viewcontrollers with pageIndex set in each 1..5
weak var delegate: NextDelegate?
nextBtn.rx.tap.asDriver().drive(onNext: {
guard let delegate = self.delegate else {return}
delegate.next(pageIndex: 1)
}).disposed(by: disposeBag)
backBtn.rx.tap.asDriver().drive(onNext: {
guard let delegate = self.delegate else {return}
delegate.previous(pageIndex: 1)
}).disposed(by: disposeBag)
My Protocol and Methods
lazy var controllers: [UIViewController] = {
let locVC = LocationVC()
locVC.delegate = self
let typeVC = TypeVC()
typeVC.delegate = self
let descVC = DescVC()
descVC.delegate = self
let priceVC = PriceVC()
descVC.delegate = self
let featuresVC = FeaturesVC()
featuresVC.delegate = self
let picturesVC = PicturesVC()
picturesVC.delegate = self
return [locVC,
typeVC, descVC, priceVC, featuresVC, picturesVC]
}()
func backBtnClicked(index: Int) {
guard index - 1 >= 0 else { return }
pageController.setViewControllers([controllers[index - 1]], direction: .reverse, animated: false, completion: nil)
}
func nextBtnClicked(index: Int) {
log("\(controllers.count)", .happy)
guard index + 1 < controllers.count else { return }
pageController.setViewControllers([controllers[index + 1]], direction: .forward, animated: false, completion: nil)
}
extension ViewController: NextDelegate {
func next(pageIndex: Int) {
print("nexteddddd \(pageIndex)")
nextBtnClicked(index: pageIndex)
}
func previous(pageIndex: Int) {
print("backedddd \(pageIndex)")
backBtnClicked(index: pageIndex)
}
}
protocol NextDelegate: AnyObject {
func next(pageIndex: Int)
func previous(pageIndex: Int)
}
The problem may relates to the fact that you set a static index 1 here
nextBtn.rx.tap.asDriver().drive(onNext: {
guard let delegate = self.delegate else {return}
delegate.next(pageIndex: 1)
}).disposed(by: disposeBag)
backBtn.rx.tap.asDriver().drive(onNext: {
guard let delegate = self.delegate else {return}
delegate.previous(pageIndex: 1)
}).disposed(by: disposeBag)
instead you need to have an index var in each vc and assign it when instantiate the vc so you can use it above or a vaibale in the main pager
Fix it
var current = 0 // assuming you set first vc initially
nextBtn.rx.tap.asDriver().drive(onNext: {
guard let delegate = self.delegate else {return}
delegate.next(pageIndex:self.current)
}).disposed(by: disposeBag)
backBtn.rx.tap.asDriver().drive(onNext: {
guard let delegate = self.delegate else {return}
delegate.previous(pageIndex:self.current)
}).disposed(by: disposeBag)
func backBtnClicked(index: Int) {
guard index - 1 >= 0 else { return }
self.current = index - 1
pageController.setViewControllers([controllers[index - 1]], direction: .reverse, animated: false, completion: nil)
}
func nextBtnClicked(index: Int) {
log("\(controllers.count)", .happy)
guard index + 1 < controllers.count else { return }
self.current = index + 1
pageController.setViewControllers([controllers[index + 1]], direction: .forward, animated: false, completion: nil)
}

Pass data on each ChildViewController to next ChildViewController on UIPageViewController

I have an object from Realm and i assign each control to object, what i want is to pass each object that i assign on each childVC to the next childVC.
I have the object initialized on my UIPageViewcontroller:
var artist = Artist()
I use this function to scroll to nextViewController :
func scrollToViewController(index newIndex: Int) {
if let firstViewController = viewControllers?.first,
let currentIndex = orderedViewControllers.index(of: firstViewController) {
let direction: UIPageViewControllerNavigationDirection = newIndex >= currentIndex ? .forward : .reverse
let nextViewController = orderedViewControllers[newIndex]
scrollToViewController(viewController: nextViewController, direction: direction)
}
}
And i assign each textbox, label to this object on childVC FirstViewController:
artist.artistName = textField.text!
Same is on the next childVC SecondViewvController:
artist.genre = genres[0]
I want to pass each control value that i assign from previous VieController to the next ViewController, for example:
On my SecondViewController i want to have the previous value saved on artist.artistName and assign the value that i get from label. For example just to print the previous value on viewDidload.
class SecondViewController {
var artistNameFromFirstVC: String?
override func viewDidLoad() {
super.viewDidLoad()
print("ArtisName: \(artistNameFromFirstVC)")
// Setup Views
setupCollectionView()
}
...
}
I have more than 2 childControllers, so i want to pass each previous values to next controllers.
I appreciate any help. Thank you :)
Helps?
struct Artist {
var name: String
var genre: String
}
class FirstViewController: UIViewController {
var name:String?
}
class SecondViewController: UIViewController {
var genre:String?
}
enum ScrollController: Int {
case first = 0
case second
init(with index: Int) {
self = ScrollController(rawValue: index) ?? .first
}
var controller: (Artist) -> UIViewController {
return { artist in
switch self {
case .first:
let controller = FirstViewController()
controller.name = artist.name
return controller
case .second:
let controller = SecondViewController()
controller.genre = artist.genre
return controller
}
}
}
}
func scrollToViewController(index newIndex: Int) {
if let firstViewController = viewControllers?.first,
let currentIndex = orderedViewControllers.index(of: firstViewController) {
let direction: UIPageViewControllerNavigationDirection = newIndex >= currentIndex ? .forward : .reverse
let nextViewController = ScrollController(with: newIndex).controller
scrollToViewController(viewController: nextViewController, direction: direction)
}
}

Dynamic number of ChildViewControllers for XLPagerTabStrip

I am using XLPagerTabStrip to create a category based reading app in Swift 4. I learnt static number of ViewControllers can be easily created using the following function.
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { }
However, the number of categories in my case depends on server response, which may change as per the need. I tried to create dynamic number of tabs by creating view controllers based on the name of categories I parsed from the json response. This is the method I did a hit and trial.
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
var childrenVC = [UIViewController]()
for eachCategory in postCategories {
print(eachCategory)
let newVC = self.storyboard?.instantiateViewController(withIdentifier: "FirstTVC") as? FirstTVC
newVC?.childName = eachCategory.name
childrenVC.append(newVC!)
self.reloadPagerTabStripView()
self.reloadInputViews()
}
return childrenVC
}
Yes, it failed. How can I achieve dynamic number of tabs in this case? If not I am also open to any other alternative. I am done with json response thing but stuck in this step. This SO answer and Github Issue didn't help as well.
I had the exact same situation. If you fetch results from the server asynchronously, as you should, you will have a crash since xlpagertabstrip needs at least one child viewcontroller.
The solution i found is to return one dummy viewcontroller at the start of the application, and after fetching data from the server to reloadPagerTabStripView.
In your parent viewcontroller you should make an empty array of your objects which you fetch from the server, for example:
var menuItems = [MenuObject]()
Next, viewControllers(for pagerTabStripController ... ) method should look like this:
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
var children = [UIViewController]()
if menuItems.count == 0 {
let child = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DummyVC") as! DummyVC
children.append(child)
return children
} else {
let menuItemsUrls = menuItems.map{$0.url}
for menuItem in menuItems {
let child = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainVC") as! TelegrafMainVC
child.name = menuItem.name.uppercased
child.url = menuItem.url
children.append(child)
}
return children
}
}
And after you fetch data from the server, whether using URLSession, or Alamofire, or whatever else, in the function or a closure you should put something like:
self.menuItems = menuItems
DispatchQueue.main.async {
self.reloadPagerTabStripView()
}
Tell me if i need to clarify something, but i believe this will be sufficient to help you.
Cheers
Step 1 : Do this in your initial viewcontroller,
class initialViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
self.loadMainView(viewControllerArray: self.setMainViewTabParameters())
}
func setMainViewTabParameters() -> NSMutableArray {
let viewControllerArray = NSMutableArray()
var tabArray = ["Tab1", "Tab2", "Tab3", "Tab4", "Tab5", "Tab6", "Tab7"]
var tabIndex = NSInteger()
for item in tabArray {
let tabString = tabArray[tabIndex]
let tabview = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YourTabControllerIdentifier") as! YourTabController
tabview.tabHeadingTitle = tabString as NSString
viewControllerArray.add(tabview)
tabIndex = tabIndex + 1
}
return viewControllerArray
}
func loadMainView(viewControllerArray : NSMutableArray) -> Void {
let mainView = self.storyboard?.instantiateViewController(withIdentifier: "YourMainControllerIdentifier") as! YourMainController
mainView.viewControllerList = viewControllerArray
self.navigationController?.pushViewController(mainView, animated: false)
}
}
Step 2:
class YourMainController: ButtonBarPagerTabStripViewController {
var viewControllerList = NSArray()
var isReload = false
//MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
guard isReload else {
return viewControllerList as! [UIViewController]
}
var childViewControllers = viewControllerList as! [UIViewController]
for (index, _) in childViewControllers.enumerated(){
let nElements = childViewControllers.count - index
let n = (Int(arc4random()) % nElements) + index
if n != index{
swap(&childViewControllers[index], &childViewControllers[n])
}
}
let nItems = 1 + (arc4random() % 8)
return Array(childViewControllers.prefix(Int(nItems)))
}
override func reloadPagerTabStripView() {
isReload = true
if arc4random() % 2 == 0 {
pagerBehaviour = .progressive(skipIntermediateViewControllers: arc4random() % 2 == 0, elasticIndicatorLimit: arc4random() % 2 == 0 )
} else {
pagerBehaviour = .common(skipIntermediateViewControllers: arc4random() % 2 == 0)
}
super.reloadPagerTabStripView()
}
}
Step 3: Your tab view controller:
class YourTabController: UIViewController, IndicatorInfoProvider {
var tabHeadingTitle = NSString()
// MARK: - Top Tab Bar Method - IndicatorInfoProvider
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return IndicatorInfo(title: tabHeadingTitle as String)
}
}
Try this
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
var childrenVC: [UIViewController] = []
for eachCategory in postCategories {
let newVC = UIStoryboard(name: "Main (YOUR-STORYBOARD-NAME)", bundle: nil).instantiateViewController(withIdentifier: "FirstTVC") as? FirstTVC
newVC?.childName = eachCategory.name
childrenVC.append(newVC!)
}
return childrenVC
}

PageViewController and screen/data refresh

I'm learning how to use a PageViewController and in the app I'm building I need to be able to refresh the content on the screen from the containing ViewController.
So in my storyboard I have:
a view controller, class RoomPageListViewController.
a view controller, class RoomContentViewController which has a number of labels which are update using CoreData.
a PageViewController
The setup is very simple, I can put in the entire code if needed but what I wanted to do is from RoomPageListViewController to be able to call a function within RoomContentViewController to update the labels and keep the user on the page that they are.
Whatever I tried has resulted in error, for example tried:
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("RoomContentViewController") as! RoomContentViewController
pageContentViewController.updateScreen()
But no luck... how can I accomplish this or am I doing it the 'wrong' way?
Thanks!
EDIT v3: With a protocol implementation now working fully!
This is the code for the RoomPageListViewController:
class RoomPageListViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var roomContentVCAccess: RoomContentVCAccess!
var roomsList: Array<String> = ["Entire Home"]
var roomButtonClicked: String = ""
let activityInd: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
var showInd: Bool = true
let shadowLabel: UILabel = UILabel(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
var viewBySelection: Int = 1
var roomDeviceGroupID: Int = 0
var redrawBool: Bool = true
var displayRoom: String = ""
var pageViewController : UIPageViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Devices By Room"
var backBtn : UIBarButtonItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
self.navigationItem.leftBarButtonItem = backBtn
self.navigationItem.leftBarButtonItem?.enabled = false
var settingsBtn : UIBarButtonItem = UIBarButtonItem(title: "Settings", style: UIBarButtonItemStyle.Plain, target: self, action: "goSettings")
self.navigationItem.rightBarButtonItem = settingsBtn
activityInd.stopAnimating()
if showInd == true {
startInd()
}
}
func startInd() {
shadowLabel.backgroundColor = UIColor.lightGrayColor()
shadowLabel.text = "Please Wait... Loading Data...\n\n\n\n\n"
shadowLabel.numberOfLines = 6
shadowLabel.textAlignment = NSTextAlignment.Center
let screenSize: CGRect = UIScreen.mainScreen().bounds
shadowLabel.center = CGPoint (x: screenSize.width/2 , y: screenSize.height/2)
shadowLabel.alpha = 0.5
shadowLabel.hidden = false
activityInd.center = CGPoint (x: screenSize.width/2 , y: screenSize.height/2)
activityInd.color = UIColor.blueColor()
activityInd.startAnimating()
activityInd.hidden = false
self.view.addSubview( shadowLabel )
self.view.addSubview( activityInd )
}
func stopInd() {
shadowLabel.hidden = true
activityInd.stopAnimating()
activityInd.hidden = true
showRooms()
if (redrawBool == true) {
//showRooms()
reset()
} else {
self.roomContentVCAccess.updateScreen()
}
redrawBool = false
}
func showRooms() {
roomsList = ["Entire Home"]
var serverSettings:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var managedContext: NSManagedObjectContext = serverSettings.managedObjectContext!
var request = NSFetchRequest(entityName: "Devices")
request.propertiesToFetch = NSArray(objects: "room") as [AnyObject]
request.resultType = NSFetchRequestResultType.DictionaryResultType
request.returnsDistinctResults = true
let deviceFilter = NSPredicate (format: "room <> %#", "Unknown")
request.predicate = deviceFilter
var roomsResults: Array<AnyObject> = managedContext.executeFetchRequest(request, error: nil)!
println("count: \(roomsResults.count)")
if roomsResults.count > 0 {
for room in roomsResults {
var theroom = room["room"] as! String
if (theroom != "Alarm") {
roomsList.append(theroom)
}
}
}
println(roomsList)
}
func reset() {
/* Getting the page View controller */
pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let pageContentViewController = self.viewControllerAtIndex(0)
self.pageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
//stopInd()
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! RoomContentViewController).pageIndex!
index++
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! RoomContentViewController).pageIndex!
if (index <= 0) {
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func viewControllerAtIndex(index : Int) -> UIViewController? {
if ((self.roomsList.count == 0) || (index >= self.roomsList.count)) {
return nil
}
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("RoomContentViewController") as! RoomContentViewController
self.roomContentVCAccess = pageContentViewController
pageContentViewController.room = self.roomsList[index]
pageContentViewController.pageIndex = index
displayRoom = self.roomsList[index]
return pageContentViewController
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return roomsList.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
and the code for RoomContentViewController:
protocol RoomContentVCAccess {
func updateScreen()
}
class RoomContentViewController: UIViewController, RoomContentVCAccess {
var pageIndex: Int?
var room : String!
#IBOutlet weak var screenScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
screenScrollView.contentSize = CGSizeMake(screenScrollView.frame.size.width, 650)
roomName.text = room
btnViewAllRoomSensors.layer.cornerRadius = 10
btnViewAllRoomSensors.layer.masksToBounds = true
updateScreen()
}
override func viewDidAppear(animated: Bool) {
updateScreen()
}
func updateScreen() {
println(room)
let roomValues = getLabelValues(room)
println(roomValues)
var roomDevicesCount: Array<Int> = roomValues[0] as! Array<Int>
// more code here....
}
func getLabelValues(roomName: String) -> (Array<AnyObject>) {
var serverSettings:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var managedContext: NSManagedObjectContext = serverSettings.managedObjectContext!
var request = NSFetchRequest(entityName: "Devices")
let deviceFilter = NSPredicate (format: "room = %#", roomName)
// more CoreData code...
}
The overall picture is that the app, once it receives data calls the stopInd() within RoomPageListViewController. From within stopInd() I need to be able to call updateScreen() that is in RoomContentViewController.
You could create a protocol that the ViewController owning the labels conforms to. For example:
protocol RoomContentVCAccess
{
func updateLabels()
}
Then in your RoomContentViewController's class declaration:
class RoomContentViewController: UIViewController, RoomContentVCAccess
{
// ...
// MARK: - RoomContentVCAccess
func updateLabels()
{
// update your labels
}
}
Your RoomPageListViewController also has to know who his roomContentVCAccess is. For that, just create an instance variable in RoomPageListViewController: var roomContentVCAccess: RoomContentVCAccess! and then say self.roomContentVCAccess = viewController as! RoomContentViewController in your viewControllerAtIndex-function.
And then when stopInd() is called in RoomPageListViewController, say self.roomContentVCAccess.updateLabels().

Resources