how to make embed in navigation controller work with scrollView - ios

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.
}
*/
}

Related

Pinch to Zoom UIImageView

I have an image view as a subview of a UIScrollView in order to enable zooming the image. It somewhat works but not well.
class LargeImageViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
if let image = selectedImage {
imageView.image = image
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}
func updateMinZoomScaleForSize(_ size: CGSize) {
let widthScale = size.width / imageView.bounds.width
let heightScale = size.height / imageView.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
#IBAction func doneTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
extension LargeImageViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
updateConstraintsForSize(view.bounds.size)
}
func updateConstraintsForSize(_ size: CGSize) {
let yOffset = max(0, (size.height - imageView.frame.height) / 2)
imageViewTopConstraint.constant = yOffset
imageViewBottomConstraint.constant = yOffset
let xOffset = max(0, (size.width - imageView.frame.width) / 2)
imageViewLeadingConstraint.constant = xOffset
imageViewTrailingConstraint.constant = xOffset
view.layoutIfNeeded()
}
}
Any ideas?
I have now tried following the tutorial suggested and it behaves a little better, but the image is zoomed in and huge.
My constraints are still giving me issues even though I followed the tutorial.
Couple reasons your code is not working like the tutorial.
1 - You missed setting the scroll view delegate (unless you set it in Storyboard). If you did not set it in Storyboard:
override func viewDidLoad() {
super.viewDidLoad()
if let image = selectedImage {
imageView.image = image
}
// add this
scrollView.delegate = self
}
2 - It will still not be quite correct, because the tutorial sets the image in Storyboard, but you're setting it in viewDidLoad(). To fix that:
// remove this
//override func viewWillLayoutSubviews() {
// super.viewWillLayoutSubviews()
// updateMinZoomScaleForSize(view.bounds.size)
//}
// add this
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateMinZoomScaleForSize(scrollView.bounds.size)
updateConstraintsForSize(scrollView.bounds.size)
}
3 - To get rid of the constraint errors in your Storyboard, give the image view Width and Height constraints (such as 100 each), and set them as Placeholders so they will not be used at run-time:
Can't say for sure where the problem is since you've probably configured the storyboard/xib file as well.
However, I recommend you to go through the guide: https://www.raywenderlich.com/5758454-uiscrollview-tutorial-getting-started.

How to access the value of a UIControl from another UIView class

Beginner question. I have a UISlider on the storyboard, and in another UIView class besides the ViewController I would like to use the slider's value to change path/shape variables within the makeShape() function.
I have tried:
a) In OtherView, try to directly reference ViewController's global variable val. This results in "unresolved identifier"
b) In ViewController, try to assign mySlider.value to a variable declared in OtherView, otherVal. This results in "Instance member 'otherVal' cannot be used on type 'OtherView'".
Could someone please help me learn how to do this correctly?
ViewController.swift:
class ViewController: UIViewController {
var val: CGFloat = 0.0
#IBOutlet weak var mySlider: UISlider!
#IBOutlet weak var otherView: UIView!
#IBAction func mySliderChanged(_ sender: Any) {
val = CGFloat(mySlider.value)
setOtherVal()
}
func setOtherVal() {
otherView.otherVal = val
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let otherView = OtherView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 100, height: 100)))
self.view.addSubview(otherView)
}
}
OtherView.swift:
class OtherView: UIView {
var path: UIBezierPath!
var otherVal: CGFloat = 0.0
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
makeShape()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func makeShape() {
let width: CGFloat = self.frame.size.width
let height: CGFloat = self.frame.size.height
let path1 = UIBezierPath(ovalIn: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 50, height: 50)))
let shapeLayer1 = CAShapeLayer()
shapeLayer1.path = path1.cgPath
shapeLayer1.fillColor = UIColor.blue.cgColor
self.layer.addSublayer(shapeLayer1)
shapeLayer1.position = CGPoint(x: otherVal, y: height)
}
}
Right now you're trying to access the otherVal property in ViewController on the class OtherVal which is shared globally through the whole app, not the property on the instance of OtherVal you've created in ViewController.
The simplest fix here is to store the OtherView instance you created in viewDidAppear and use that property to update the view.
class ViewController: UIViewController {
var val: Float = 0.0
#IBOutlet weak var mySlider: UISlider!
// Add a property to hold on to the view after you create it.
var otherView: OtherView?
#IBAction func mySliderChanged(_ sender: Any) {
val = mySlider.value
setOtherVal()
}
func setOtherVal() {
// `val` is a Float and `otherVal` is a `CGFloat` so we have to convert first.
let newValue = CGFloat(self.val)
// Use the property that's holding your view to update with the new value from the slider.
self.otherView?.otherVal = newValue
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let otherView = OtherView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 100, height: 100)))
// Set the property to the view you just created so you can update it later.
self.otherView = otherView
self.view.addSubview(otherView)
}
}
Currently though it doesn't look like you're actually updating OtherView once the new value is set, so you'll want to do something similar there. Keep a reference to the CAShapeLayer you create and update the position when otherVal changes.
Also note viewDidAppear can be called multiple times throughout a view controller's life cycle. If you only want to add the view once, you should use viewDidLoad which will guarantee you have a freshly created self.view to work with.
Edit: As mentioned in the comments, you can also set up a custom view in the storyboard / nib and create an outlet. Right now it doesn't look like your code is set up to work with that though.

Class 'ProductDetailViewController' has no initializers

I am trying to create scrollable imageview. Currently using swift 4.0. While running I am getting "has no initializers" error. I am not sure what code brought this error. I am new to swift and I am unable to track what is going on.
Class 'ProductDetailViewController' has no initializers I am getting this error.
Can any one please tell me how to fix this error.
Entire view controller code is given below. Thanks in advance
import UIKit
import SwiftyJSON
class ProductDetailViewController: UIViewController,UIScrollViewDelegate {
//Outlers
#IBOutlet weak var scrollView: UIScrollView!
//Global variables
var productDict : JSON = []
var arrayOfProductImageUrls : Array<Any> = []
var zoomScroll : UIScrollView
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.initialSetup()
self.scrollViewSetup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
//Mark: - Scrollview Setup
func initialSetup() {
self.scrollView.delegate = self
}
func scrollViewSetup() {
let productsArray : Array = self.arrayOfProductImageUrls;
self.scrollView.backgroundColor = UIColor.white
var frame : CGRect = CGRectMake(0, 0, self.scrollView.frame.size.width, 360)
for (index, value) in productsArray.enumerated() {
//Imageview Setup
let productImageView : UIImageView
let width : NSInteger = Int(frame.width)
productImageView.frame.origin.x = CGFloat(Int (width * index))
productImageView.frame.origin.y = 0
//Scrollview Setup
zoomScroll.frame = frame;
zoomScroll.backgroundColor = UIColor.clear
zoomScroll.showsVerticalScrollIndicator = false
zoomScroll.showsHorizontalScrollIndicator = false
zoomScroll.delegate = self
zoomScroll.minimumZoomScale = 1.0
zoomScroll.maximumZoomScale = 6.0
zoomScroll.tag = index
zoomScroll.isScrollEnabled = true
self.scrollView.addSubview(zoomScroll)
//Setting image
let imageUrl : URL = (productsArray[index] as AnyObject).url
productImageView.sd_setImage(with: imageUrl)
if index < productsArray.count {
productImageView.frame = zoomScroll.bounds
productImageView.contentMode = UIViewContentMode.redraw
productImageView.clipsToBounds = true
productImageView.backgroundColor = UIColor.clear
zoomScroll.addSubview(productImageView)
}
self.scrollView.contentSize = CGSizeMake(CGFloat(frame.origin.x) + CGFloat(width), productImageView.frame.size.height)
}
}
//Mark : Custom methods
func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
return CGRect(x: x, y: y, width: width, height: height)
}
func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
}
#Saurabh Prajapati. Nice and quick catch.
For more, The Swift Programming Language states
Classes and structures must set all of their stored properties to an
appropriate initial value by the time an instance of that class or
structure is created. Stored properties cannot be left in an
indeterminate state.
You can set an initial value for a stored property within an
initializer, or by assigning a default property value as part of the
property’s definition.
Let me explain more, the problem was with scrollView property that does not have a default value. As above mentioned, all variables in Swift must always have a value or nil (make it optional). When you make it optional, you allow it to be nil by default, removing the need to explicitly give it a value or initialize it.
Here we are using ! optional so the default value will be nil
class ViewController : UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
}
Setting nil as the default value
class ViewController : UIViewController {
#IBOutlet weak var scrollView: UIScrollView! = nil
}
Setting the default value, creating an object now it is not nil.
class ViewController : UIViewController {
#IBOutlet weak var scrollView: UIScrollView = UIScrollView()
}
But we can't-do like that, we are not setting the default value here.
class ViewController : UIViewController {
#IBOutlet weak var scrollView: UIScrollView
}
I hope it will help.
I had the same echo
it was so easy to solve it by using ! after any variable like this
var ref: DatabaseReference!

Swift 3 UIScrollview not asking zooming

This is driving me nuts!
I'm basing my UIScrollView on http://koreyhinton.com/blog/uiscrollview-crud.html to make it programatic, so have set up a container view inside my scrollview. But it pans, but won't zoom.
class BinaryTreeViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
var containerView : UIView!
override func viewDidLoad() {
super.viewDidLoad()
let width:CGFloat = self.view.bounds.width
let height:CGFloat = self.view.bounds.height
scrollView = UIScrollView()
scrollView.delegate = self
scrollView.minimumZoomScale = 0.5
scrollView.maximumZoomScale = 2.0
scrollView.contentSize = CGSize(width: width*2, height: 2000)
scrollView.backgroundColor = .red
containerView = UIView()
scrollView.addSubview(containerView)
view.addSubview(scrollView)
containerView.isUserInteractionEnabled = true
scrollView.isUserInteractionEnabled = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
}
override func viewWillLayoutSubviews() {
//I create a view called "theView"
containerView.addSubview(theView)
}
The following functions do not fire at any point
func update(zoomScale: CGFloat, offSet: CGPoint) {
scrollView.zoomScale = zoomScale
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return containerView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
NSLog("scroll")
}
You really don't need to do so much code for that purpose.
You can set up all you need for scrollView in storyboard, and you only need outlet for the view you wish to zoom.
Set up a controller, add scrollview, connect delegate property to view controller, add zooming view as subview in IB.
In the class, conform controller to UIScrollViewDelegate, and use viewForZooming, a scrollView delegate method.
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var zoomer: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomer
}
}
P.S. Use newer resources for learning, Ray Wenderlich, AppCoda, etc - its a big web full of good sources, and Swift is in constant change.

Why my viewcontrollers are not being shown on scrollview controller?

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. :/

Resources