Why my viewcontrollers are not being shown on scrollview controller? - ios

I have three step view controllers. I'm trying to display those three steps on a single viewcontroller (RegisterViewController) using a scroll view so that users can swipe through the steps.
I saw some other posts and got this far. When I run the app I'm getting a blank screen with the background color of the RegisterViewController. I wrote some println statements in the step view controllers to check whether they are being instantiated or not and I could see those statements' output on console. Please if anybody can help?
class RegisterViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var registerStepsPageControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
setupScrollView()
}
func setupScrollView() {
let storyboard = UIStoryboard(name: "Login", bundle: nil)
let stepOneViewController = storyboard.instantiateViewControllerWithIdentifier("RegisterStepOne") as! RegisterStepOneViewController
let stepTwoViewController = storyboard.instantiateViewControllerWithIdentifier("RegisterStepTwo") as! RegisterStepTwoViewController
let stepThreeViewController = storyboard.instantiateViewControllerWithIdentifier("RegisterStepThree") as! RegisterStepThreeViewController
var stepViewControllers = [stepOneViewController, stepTwoViewController, stepThreeViewController]
for index in 0..<stepViewControllers.count {
self.addChildViewController(stepViewControllers[index])
let originX: CGFloat = CGFloat(index) * CGRectGetWidth(self.scrollView.frame);
stepViewControllers[index].view.frame = CGRectMake(originX, 0, self.view.frame.size.width, self.view.frame.size.height);
stepViewControllers[index].view.frame.size = self.view.frame.size
self.scrollView.addSubview(stepViewControllers[index].view)
stepViewControllers[index].didMoveToParentViewController(self)
}
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(stepViewControllers.count), self.view.frame.height)
self.scrollView.delegate = self
self.registerStepsPageControl.numberOfPages = stepViewControllers.count
}
}
EDIT01:
This code below works. It loads the images and they are being displayed as they are supposed to. But I don't know what might be the problem while loading views from other viewcontrollers.
#IBOutlet weak var tutorialStepsPageControl: UIPageControl!
#IBOutlet weak var scrollView: UIScrollView!
var stepImages: [UIImage] = [UIImage(named: "tutorial_image_step1")!, UIImage(named: "tutorial_image_step2")!, UIImage(named: "tutorial_image_step3")!]
override func viewDidLoad() {
super.viewDidLoad()
self.tutorialStepsPageControl.numberOfPages = stepImages.count
setupScrollView()
}
func setupScrollView() {
var imageFrame: CGRect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
var imageView: UIImageView!
for index in 0..<stepImages.count {
imageFrame.origin.x = self.view.frame.size.width * CGFloat(index)
imageFrame.size = self.view.frame.size
imageView = UIImageView(frame: imageFrame)
imageView.image = stepImages[index]
imageView.contentMode = .ScaleAspectFit
self.scrollView.addSubview(imageView)
}
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(stepImages.count), self.view.frame.size.height)
self.scrollView.delegate = self
}

Try moving the line:
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(stepViewControllers.count), self.view.frame.height)
Above this line:
for index in 0..<stepViewControllers.count {
This issue might be coming from the fact that you're adding the subviews before you sent the contentSize.

Okay I deleted the step controllers and added them again from scratch. Did a clean build and now it's working. Don't know what was I doing wrong. :/

Related

how to make embed in navigation controller work with scrollView

I have watched this tutorial
Snapchat Like Layout using View Controller Theme
then I embed one of the three controllers in Navigation Controller but it didn't work then i have tried to add it on the view controller how had the scroll view also didn't work + gives me overlap I didn't tried it in code tho but I don't think this is the cause , this is the code
class ViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let V1 = self.storyboard?.instantiateViewController(withIdentifier: "V1") as UIViewController!
self.addChildViewController(V1!)
self.scrollView.addSubview((V1?.view)!)
V1?.didMove(toParentViewController: self)
V1?.view.frame = scrollView.bounds
let V2 = self.storyboard?.instantiateViewController(withIdentifier: "V2") as UIViewController!
self.addChildViewController(V2!)
self.scrollView.addSubview((V2?.view)!)
V2?.didMove(toParentViewController: self)
V2?.view.frame = scrollView.bounds
var V2Frame: CGRect = V2!.view.frame
V2Frame.origin.x = self.view.frame.width
V2?.view.frame = V2Frame
let V3 = self.storyboard?.instantiateViewController(withIdentifier: "V3") as UIViewController!
self.addChildViewController(V3!)
self.scrollView.addSubview((V3?.view)!)
V3?.didMove(toParentViewController: self)
V3?.view.frame = scrollView.bounds
var V3Frame: CGRect = V3!.view.frame
V3Frame.origin.x = 2 * self.view.frame.width
V3?.view.frame = V3Frame
self.scrollView.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.height)
self.scrollView.contentOffset = CGPoint(x: self.view.frame.width * 1 , y: self.view.frame.height)
}
how the code works ??
1- first I have added scroll view to a view controller
2- then inside the scroll view I have added 3 view controller and all the 3 controllers has own class like normal view controllers
3- the scroll View added the 3 controllers on its view by this code on the top
all the 3 controllers inheriting from own class and everything is wor fine
if anyone can help or need more description just ask
try below
Create ViewController in Storyboard or XIB and add ScrollView and PageControl
My Class as below:
class ScrollContentViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var pageControl: UIPageControl!
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.pageControl.currentPage = 0
self.pageControl.numberOfPages = 4
var originX = CGFloat(0)
let width = scrollView.frame.size.width
let height = scrollView.bounds.size.height
for x in 0 ..< 4 {
let V1 = UIViewController()
self.scrollView.addSubview(V1.view)
V1.view.frame = CGRect(x: originX, y: 0, width: width, height: height)
V1.view.backgroundColor = x % 2 == 0 ? UIColor.lightGray : UIColor.darkGray
self.addChildViewController(V1)
originX += width
}
self.scrollView.contentSize = CGSize(width: originX, height: height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let x = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
self.pageControl.currentPage = x
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}

Swift - scroll bar swipe function

This is Alibaba.com's ios application. In the app, if I swipe left the bar will scroll left and reveal more clickable options. My question is, how is this made?
Thanks!
I solved it.
1. Firstly make a .xib file, name it to whatever you want, I named mine to unnamedView, then add the labels and imageViews.
2. Then create UnnamedView class file like this and add all labels and images
class unnamedView: UIView {
#IBOutlet weak var firstButton: UIButton!
#IBOutlet weak var firstImage: UIImageView!
#IBOutlet weak var firstLabel: UILabel!
}
3. Then create a array for the UnnamedView in the main view controller.
let unnamed = ["title1":"textTitleToLabel","image1":"nameOfImage"]
var unnamedArray = [Dictionary<String,String>]()
4. Then I added the scroll view to the main view controller
#IBOutlet weak var unnamedScrollView: UIScrollView!
5. Inside viewDidLoad() add following
unnamedArray = [unnamed]
unnamedScrollView.isPagingEnabled = true
unnamedScrollView.contentSize = CGSize(width: unnamedScrollView.bounds.width * CGFloat(unnamedArray.count), height: 100)
unnamedScrollView.showsHorizontalScrollIndicator = false
unnamedScrollView.delegate = self
loadUnnamed()
6. And lastly added following bellow the viewDidLoad
func loadCategories() {
for (index, category) in categoriesArray.enumerated() {
if let unnamedView = Bundle.main.loadNibNamed("unnamedView", owner: self, options: nil)?.first as? unnamedView {
unnamedView.firstImage.image = UIImage(named: category["image1"]!)
unnamedView.firstLabel.text = category["title1"]
unnamedView.firstButton.tag = index
unnamedView.firstButton.addTarget(self, action: #selector(ViewController.gotoCategory(sender:)), for: .touchUpInside)
unnamedScrollView.addSubview(unnamedView)
unnamedView.frame.size.width = self.view.bounds.size.width
unnamedView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width
}
}
}
func gotoCategory (sender:UIButton) {
print("The user wants to buy feature \(sender.tag)")
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "tableView")
self.present(newViewController, animated: true, completion: nil)
}
And also, if you'd like to add page control dots, simply to this.
#IBOutlet weak var featurePageControl: UIPageControl!
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x / scrollView.frame.size.width
featurePageControl.currentPage = Int(page)
}

UIView doesn't center properly in UIScrollView with autolayout

I'm making an application where I need an x amount of custom UIView and place them in a scrollView. The layout of the scrollView and the UIView xib are set with AutoLayout. The result I'm getting now is this:
First View is well centred in ScrollView
Second View is wrong and has a lot of space in between
See my VC Code under here.
let sponsors = Sponsors.createSponsors() <-- Array
override func viewDidLoad() {
super.viewDidLoad()
configureSponsors()
}
//MARK: Load the AddView in ScrollView
func configureSponsors() {
self.scrollView.contentSize = CGSizeMake(CGFloat(sponsors.count) * self.scrollView.frame.size.width, self.scrollView.frame.size.height)
for sponsor in sponsors {
numberOfItems++
let addView = NSBundle.mainBundle().loadNibNamed("AddView", owner: self, options: nil).last as! AddView
addView.addDataToAddView(sponsor)
addView.frame = CGRectMake(CGFloat(numberOfItems - 1) * scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)
self.scrollView.addSubview(addView)
}
}
And here is my UIView code:
//MARK: Outlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var sponsorTitle: UILabel!
#IBOutlet weak var sponsorLogo: UIImageView!
#IBOutlet weak var sponsorSubtitle: UILabel!
#IBOutlet weak var roundView: UIView!
#IBOutlet weak var playMusicButton: UIButton!
//MARK: Properties
var cornerRadius: CGFloat = 3.0
func addDataToAddView(sponsor: Sponsors) {
backgroundImageView.image = UIImage(named: sponsor.backgroundImage)
sponsorLogo.image = UIImage(named: sponsor.logoImage)
sponsorTitle.text = sponsor.title
sponsorSubtitle.text = sponsor.subTitle
}
override func layoutSubviews() {
roundView.layer.cornerRadius = roundView.frame.size.width / 2
roundView.alpha = 0.7
roundView.clipsToBounds = true
}
//MARK: PlayVideo
#IBAction func playVideo(sender: UIButton) {
//play music
}
I've already searched for the same problems. I found out that I have to use the Pure Auto Layout Approach. Should that mean I need to programatically set the constraints for the UIView?
Many thanks,
Dax
Update:
Pictures for scrollView setup:
You should not perform layout calculations in viewDidLoad as frames are not set correctly till then.
Correct place to do this is either viewWillLayoutSubviews or viewDidLayoutSubviews as you will get the correct frame data when these functions are called

Im trying to create a slide ViewController like snapchats

I copied this code for the sliding view controller from a YouTube snapchat like menu video but it won't compile.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var V1 : View1 = View1(nibName: "View1" , bundle: nil)
self.addChildViewController(V1)
self.scrollView.addSubview(V1.view)
V1.didMoveToParentViewController(self)
}
I keep getting the error use of undeclared type 'View1'. How do I fix this? I followed a tutorial and the code is identical. How do I declare View1 as a type?
I've made the same tutorial but for three Views:
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let view1: View1 = View1(nibName: "View1", bundle: nil)
addChildViewController(view1)
scrollView.addSubview(view1.view)
view1.didMoveToParentViewController(self)
let view2: View2 = View2(nibName: "View2", bundle: nil)
addChildViewController(view2)
scrollView.addSubview(view2.view)
view2.didMoveToParentViewController(self)
var view2Frame: CGRect = view2.view.frame
view2Frame.origin.x = view.frame.width
view2.view.frame = view2Frame
let view3: View3 = View3(nibName: "View3", bundle: nil)
addChildViewController(view3)
scrollView.addSubview(view3.view)
view3.didMoveToParentViewController(self)
var view3Frame: CGRect = view3.view.frame
view3Frame.origin.x = view.frame.width * 2
view3.view.frame = view3Frame
self.scrollView.contentSize.width = view.frame.width * 3
}
And this works just fine. Hope it helps.

how can make a image slideShow in ios using swift its only show one image?

import UIKit
class PageViewController: UIViewController {
#IBOutlet weak var myScrView: UIScrollView!
#IBOutlet weak var pagectr: UIPageControl!
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
myScrView.tag = 1
myScrView.autoresizingMask = UIViewAutoresizing.None
self.view.addSubview(myScrView)
self.setupScrollView(myScrView)
pagectr.tag = 12
pagectr.numberOfPages = 9
pagectr.autoresizingMask = UIViewAutoresizing.None
self.view.addSubview(pagectr)
}
func setupScrollView(scrMain:UIScrollView) -> Void {
var imgesArray : NSMutableArray = []
for position in 1...9 {
var strImage : String = "\(position).jpeg"
var imges = UIImage(named: strImage)
imgesArray.addObject(imges!)
imageView.contentMode = UIViewContentMode.ScaleToFill
imageView.image = imges
imageView.tag = position+1
scrMain.addSubview(imageView)
println(imageView)
}
scrMain.contentSize = CGSizeMake(scrMain.frame.size.width*10, scrMain.frame.size.height)
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "scrollingTimer", userInfo:nil, repeats: true)
}
func scrollingTimer(){
let scrMain: UIScrollView = self.view.viewWithTag(1) as UIScrollView
let pgctr: UIPageControl = self.view.viewWithTag(12) as UIPageControl
let contentOffset = scrMain.contentOffset.x as CGFloat
var nextPage = (CGFloat)(contentOffset/scrMain.frame.size.width) + 1
if(nextPage != 9){
scrMain.scrollRectToVisible(CGRectMake(nextPage*scrMain.frame.size.width, 0, scrMain.frame.size.width, scrMain.frame.size.height), animated: true)
pgctr.currentPage = Int(nextPage)
}
else{
scrMain.scrollRectToVisible(CGRectMake(0, 0, scrMain.frame.size.width, scrMain.frame.size.height), animated: true)
pgctr.currentPage = 1
}
}
}
I want to make a image slide show app using swift in ios please help me it's show only one image.I get a blank screen, almost as if the animations aren't keeping up, and then when I wait a moment and swipe again the image views speed up into place and works normally again. Any idea what I'm doing wrong? What is the best practice when it comes to implementing an image carousel like this with a dynamic amount of images (here they're hardcoded)?

Resources