Starting an action when View Controller Loads - ios

How do I start an action when the view controller loads on screen?
I've managed to do the function I want with an #IBAction but I don't want a button press for the action to happen, I want it to start the action when the page loads
any thoughts?
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
#IBAction func Animate(sender: AnyObject) {
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}

Use :-
Basic idea here is that whenever your view will load corresponding class will look up to viewWillAppear(animated: Bool) function and if it's present in the code it will execute all the code in it.The moment that particular view is about to appear on your UI, your code block in viewWillAppear(animated: Bool) will get called.
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
}
override func viewWillAppear(animated :Bool) {
super.viewWillAppear(animated)
progressActn()
//Setting up your progress layer
animateActn()
//Animating that progress layer
}
#IBAction func Animate(sender: AnyObject) {
animateActn()
}
func animateActn(){
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}
}
}
func progressActn(){
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
}

Related

how to make collapsible/expandable views in swift

I created a collapsible/expandable form on android. please see GIF below
https://giphy.com/gifs/zVvcKtgT9QTaa1O29O
I'm trying to create something similar on ios, so far, i've already created the bottom sheet as seen below
Looking at this GIF https://gfycat.com/dismalbronzeblowfish, you'd notice i'm able to expand and collapse the views, but there's a big gap where the view used to be, the expected behavior is that the space collapses also with an animation
Below is the code for the bottom sheet
class BottomSheetViewController: UIViewController {
// holdView can be UIImageView instead
#IBOutlet weak var holdView: UIView!
#IBOutlet weak var left: UIButton!
#IBOutlet weak var right: UIButton!
#IBOutlet weak var pickupView: UIView!
#IBOutlet weak var deliveryView: UIView!
#IBOutlet weak var deliverydetailsView: UIView!
#IBOutlet weak var pickupDetailsVIew: UIControl!
let fullView: CGFloat = 100
var partialView: CGFloat {
return UIScreen.main.bounds.height - 300
}
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
view.addGestureRecognizer(gesture)
let pickupTapGesture = UITapGestureRecognizer(target: self, action: #selector(pickupButton))
let deliveryTapGesture = UITapGestureRecognizer(target: self, action: #selector(deliveryButton))
pickupView.addGestureRecognizer(pickupTapGesture)
deliveryView.addGestureRecognizer(deliveryTapGesture)
pickupView.setBorder(radius: 5, color: .black)
deliveryView.setBorder(radius: 5, color: .black)
roundViews()
deliverydetailsView.isHidden = true
pickupDetailsVIew.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareBackgroundView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.6, animations: { [weak self] in
let frame = self?.view.frame
let yComponent = self?.partialView
self?.view.frame = CGRect(x: 0, y: yComponent!, width: frame!.width, height: frame!.height)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func rightButton(_ sender: AnyObject) {
print("clicked")
}
#objc func pickupButton(_ sender: UITapGestureRecognizer) {
print("tap")
if pickupDetailsVIew.isHidden {
expand(pickupDetailsVIew)
collapse(deliverydetailsView)
} else {
collapse(pickupDetailsVIew)
}
}
#objc func deliveryButton(_ sender: UITapGestureRecognizer) {
print("tap")
if deliverydetailsView.isHidden {
expand(deliverydetailsView)
collapse(pickupDetailsVIew)
} else {
collapse(deliverydetailsView)
// if deliveryView.isHidden && pickupDetailsVIew.isHidden {
//
// }
}
}
func expand(_ view: UIView) {
view.isHidden = false
}
func collapse(_ view: UIView) {
view.isHidden = true
}
// #IBAction func close(_ sender: AnyObject) {
// UIView.animate(withDuration: 0.3, animations: {
// let frame = self.view.frame
// self.view.frame = CGRect(x: 0, y: self.partialView, width: frame.width, height: frame.height)
// })
// }
#objc func panGesture(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
let velocity = recognizer.velocity(in: self.view)
let y = self.view.frame.minY
if ( y + translation.y >= fullView) && (y + translation.y <= partialView ) {
self.view.frame = CGRect(x: 0, y: y + translation.y, width: view.frame.width, height: view.frame.height)
recognizer.setTranslation(CGPoint.zero, in: self.view)
}
if recognizer.state == .ended {
var duration = velocity.y < 0 ? Double((y - fullView) / -velocity.y) : Double((partialView - y) / velocity.y )
duration = duration > 1.3 ? 1 : duration
UIView.animate(withDuration: duration, delay: 0.0, options: [.allowUserInteraction], animations: {
if velocity.y >= 0 {
self.view.frame = CGRect(x: 0, y: self.partialView, width: self.view.frame.width, height: self.view.frame.height)
} else {
self.view.frame = CGRect(x: 0, y: self.fullView, width: self.view.frame.width, height: self.view.frame.height)
}
}, completion: nil)
}
}
func roundViews() {
view.layer.cornerRadius = 5
holdView.layer.cornerRadius = 3
// left.layer.cornerRadius = 10
// right.layer.cornerRadius = 10
// left.layer.borderColor = UIColor(red: 0, green: 148/225, blue: 247.0/255.0, alpha: 1).cgColor
// left.layer.borderWidth = 1
view.clipsToBounds = true
}
func prepareBackgroundView(){
// let blurEffect = UIBlurEffect.init(style: .dark)
// let visualEffect = UIVisualEffectView.init(effect: blurEffect)
// let bluredView = UIVisualEffectView.init(effect: blurEffect)
// bluredView.contentView.addSubview(visualEffect)
//
// visualEffect.frame = UIScreen.main.bounds
// bluredView.frame = UIScreen.main.bounds
//
// view.insertSubview(bluredView, at: 0)
}
}
I need some help/pointers in the right direction from anyone who has done this before, or who knows how to do this
Thank you

Image Zoom Scale is Not Resetting

So I have two buttons (which have images attached to them) in my view controller. When either is clicked there is a centered popup of that image.
The problem is, that the 1st button's image does not reset its zoom scale and position after use (the second does). So when you click on the image the second time, it is still zoomed in, and misaligned.
Here is the code for the zoom feature only:
//popup window
#IBOutlet var imageView1: UIView!
#IBOutlet var imageView2: UIView!
//scroll view
#IBOutlet weak var scrollView1: UIScrollView!
#IBOutlet weak var scrollView2: UIScrollView!
//image
#IBOutlet weak var zoomImageView1: UIImageView!
#IBOutlet weak var zoomImageView2: UIImageView!
//background is dimmed when the popup window is active
#IBOutlet weak var backgroundButton: UIButton!
var button1Pressed = false
var button2Pressed = false
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView1.minimumZoomScale = 1.0
self.scrollView1.maximumZoomScale = 6.0
self.scrollView2.minimumZoomScale = 1.0
self.scrollView2.maximumZoomScale = 6.0
}
//this might be the problem code, not sure how to fix it though
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
if button1Pressed == true {
return self.zoomImageView1
} else {
return self.zoomImageView2
}
}
//resizes zoomed image when orientation changes
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if UIDevice.current.orientation.isLandscape{
imageView1.center = self.view.center
imageView2.center = self.view.center
imageView1.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
imageView2.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
scrollView1.zoomScale = 1.0
scrollView2.zoomScale = 1.0
} else if UIDevice.current.orientation.isPortrait{
imageView1.center = self.view.center
imageView2.center = self.view.center
imageView1.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
imageView2.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
scrollView1.zoomScale = 1.0
scrollView2.zoomScale = 1.0
}
}
//activates the 1st image
#IBAction func showImageView1(_ sender: Any) {
animateIn1()
button1Pressed = true
}
//activates the 2nd image
#IBAction func showImageView2(_ sender: Any) {
animateIn2()
button2Pressed = true
}
//closes either image
#IBAction func closeImageView(_ sender: Any) {
animateOut()
button1Pressed = false
button2Pressed = false
}
func animateIn1() {
self.scrollView1.zoomScale = 1.0
self.view.addSubview(imageView1)
imageView1.center = self.view.center
imageView1.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
imageView1.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
imageView1.alpha = 0
self.backgroundButton.alpha = 0.7
UIView.animate(withDuration: 0.4) {
self.imageView1.alpha = 1
self.imageView1.transform = CGAffineTransform.identity
}
}
func animateIn2() {
self.scrollView2.zoomScale = 1.0
self.view.addSubview(imageView2)
imageView2.center = self.view.center
imageView2.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
imageView2.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
imageView2.alpha = 0
self.backgroundButton.alpha = 0.7
UIView.animate(withDuration: 0.4) {
self.imageView2.alpha = 1
self.imageView2.transform = CGAffineTransform.identity
}
}
func animateOut() {
if button1Pressed == true {
UIView.animate(withDuration: 0.3, animations: {
self.imageView1.transform = CGAffineTransform(scaleX: 1, y: 1)
self.imageView1.alpha = 0
self.backgroundButton.alpha = 0
}) { (success:Bool) in
self.imageView1.removeFromSuperview()
}
} else if button2Pressed == true {
UIView.animate(withDuration: 0.3, animations: {
self.imageView2.transform = CGAffineTransform(scaleX: 1, y: 1)
self.imageView2.alpha = 0
self.backgroundButton.alpha = 0
}) { (success:Bool) in
self.imageView2.removeFromSuperview()
}
}
}
It's probably something simple.
Any help would be greatly appreciated.
Instead of checking for button1Pressed == true you should rather check which scrollview is given as an argument:
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
if scrollView == scrollView1 {
return self.zoomImageView1
} else {
return self.zoomImageView2
}
}

UIViewAnimationTransition flip UIImageView

Video
My UIView.transitions in my tapped function at the bottom works the first time but the second time for my else statement to flip back to the front side crashes every time. Getting error message "fatal error: unexpectedly found nil while unwrapping an Optional value". Want to successfully flip front to back and back to front every time :) thanks you in advance pals. ;) Also, I added my ImageOne & ImageTwo views in my storyboard!
import UIKit
import Foundation
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
#IBOutlet weak var mainScrollView: UIScrollView!
#IBOutlet weak var imageOne: UIImageView!
#IBOutlet weak var imageTwo: UIImageView!
var myImageArray = [UIImage]()
var myImageArray2 = [UIImage]()
var back: UIImageView!
var front: UIImageView!
var showingFront = true
override func viewDidLoad() {
super.viewDidLoad()
SignedIn()
self.view.addGestureRecognizer(revealViewController().panGestureRecognizer())
let singleTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapped))
singleTap.numberOfTapsRequired = 1
mainScrollView.addGestureRecognizer(singleTap)
mainScrollView.isUserInteractionEnabled = true
mainScrollView.frame = view.frame
myImageArray = [image1, image2 ,image3, image4, image5]
myImageArray2 = [imageText1, imageText2 ,imageText3, imageText4, imageText5]
for i in 0..<myImageArray.count {
front = UIImageView()
front.image = myImageArray[i]
front.contentMode = .scaleToFill
let yPosition = self.view.frame.height * CGFloat(i) + self.view.frame.height/2 - (self.view.frame.height / 1.1)/2
let xPosition = self.view.frame.width/2 - (self.view.frame.width / 1.1)/2
front.frame = CGRect(x: xPosition, y: yPosition, width: self.view.frame.width / 1.1, height: self.view.frame.height / 1.1)
front.layer.borderWidth = 5
back = UIImageView()
back.image = myImageArray2[i]
back.contentMode = .scaleToFill
back.frame = CGRect(x: xPosition, y: yPosition, width: self.view.frame.width / 1.1, height: self.view.frame.height / 1.1)
back.layer.borderWidth = 5
mainScrollView.contentSize.height = mainScrollView.frame.height * CGFloat(i + 1)
imageOne.addSubview(front)
imageTwo.addSubview(back)
}
}
func tapped() {
print("Hello")
if (showingFront) {
UIView.transition(from: imageOne, to: imageTwo, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
showingFront = false
} else {
UIView.transition(from: imageTwo, to: imageOne, duration: 1, options: UIViewAnimationOptions.transitionFlipFromLeft, completion: nil)
showingFront = true
}
}
}
You need to add a second animation option to keep the "from" view in play. Here's how I do it:
// declare the animation options
let transitionOptions: UIViewAnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews]
func tapped() {
print("Hello")
if (showingFront) {
UIView.transition(from: imageOne, to: imageTwo, duration: 1, options: transitionOptions, completion: nil)
showingFront = false
} else {
UIView.transition(from: imageTwo, to: imageOne, duration: 1, options: transitionOptions, completion: nil)
showingFront = true
}
}
I recall that it took me a solid hour to add a second option, as Swift 2 code you could do it differently.

How to change Modal Popup size to equal to its superview size?

I created a modal popup in storyboard, so that when an image is clicked there is a popup of that image, but resizable. All I want is so that the popup is equal to the size of the superview (programmatically).
I will provide additional code if needed.
#IBOutlet var imageView: UIView!
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var zoomImageView: UIImageView!
#IBOutlet weak var backgroundButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: false)
imageView.layer.cornerRadius = 10
imageView.layer.masksToBounds = true
self.scrollView.minimumZoomScale = 1.0
self.scrollView.maximumZoomScale = 6.0
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.zoomImageView
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if UIDevice.current.orientation.isLandscape{
imageView.center = self.view.center
imageView.frame = view.frame
} else if UIDevice.current.orientation.isPortrait{
imageView.center = self.view.center
imageView.frame = view.frame
}
}
#IBAction func showImageView(_ sender: Any) {
animateIn()
}
#IBAction func closeImageView(_ sender: Any) {
animateOut()
}
func animateIn() {
self.scrollView.zoomScale = 1.0
self.view.addSubview(imageView)
imageView.center = self.view.center
imageView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
imageView.alpha = 0
self.backgroundButton.alpha = 0.7
UIView.animate(withDuration: 0.4) {
self.imageView.alpha = 1
self.imageView.transform = CGAffineTransform.identity
}
}
func animateOut() {
UIView.animate(withDuration: 0.3, animations: {
self.imageView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
self.imageView.alpha = 0
self.backgroundButton.alpha = 0
}) { (success:Bool) in
self.imageView.removeFromSuperview()
}
}
}
Any help would be greatly appreciated.
Finally found the answer.
Instead of:
imageView.frame = self.view.frame
I just had to use:
imageView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
And in the animateOut() block I changed the transform scale to 1
self.image.transform = CGAffineTransform(scaleX: 1, y: 1)
All that fixed the problem.

How to create a Scroll View with a page control using swift? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am trying to create a Page View controller with numbers of view. I want a simple code sample that will use UIPageViewController.
import UIKit
class DummyVC: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView(frame: CGRect(x:0, y:0, width:320,height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))
override func viewDidLoad() {
super.viewDidLoad()
configurePageControl()
scrollView.delegate = self
scrollView.isPagingEnabled = true
self.view.addSubview(scrollView)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
let subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
self.scrollView .addSubview(subView)
}
self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
}
For lazy coder this is the Swift 3 implementation based on That lazy iOS Guy 웃's answer
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configurePageControl()
scrollView.delegate = self
self.view.addSubview(scrollView)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
let subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
self.scrollView .addSubview(subView)
}
self.scrollView.isPagingEnabled = true
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * 4, height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Swift 3 - Horizontal image scroll
import UIKit
class pageenabled: UIViewController,UIScrollViewDelegate
{
let imagelist = ["img1.jpg", "photo1.jpg", "photo3.jpg", "photo4.jpg", "photo5.jpg"]
var scrollView = UIScrollView()
var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))
var yPosition:CGFloat = 0
var scrollViewContentSize:CGFloat=0;
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300))
configurePageControl()
scrollView.delegate = self
self.view.addSubview(scrollView)
for i in stride(from: 0, to: imagelist.count, by: 1) {
var frame = CGRect.zero
frame.origin.x = self.scrollView.frame.size.width * CGFloat(i)
frame.origin.y = 0
frame.size = self.scrollView.frame.size
self.scrollView.isPagingEnabled = true
let myImage:UIImage = UIImage(named: imagelist[i])!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.scaleAspectFit
myImageView.frame = frame
scrollView.addSubview(myImageView)
}
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * CGFloat(imagelist.count), height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: Selector(("changePage:")), for: UIControlEvents.valueChanged)
// Do any additional setup after loading the view.
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = imagelist.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In Swift 3.0
craeate iboutlets through story board for scrollview and pagecontroller.
#IBOutlet weak var imgScrollView: UIScrollView!
#IBOutlet weak var imgPageController: UIPageControl!
var sliderImagesArray = NSMutableArray()
in viewdidload method write this code
sliderImagesArray = ["https://images.unsplash.com/photo-1432679963831-2dab49187847?w=1080","https://images.unsplash.com/photo-1447746249824-4be4e1b76d66?w=1080", "https://images.unsplash.com/photo-1463595373836-6e0b0a8ee322?w=1080"]
imgScrollView.delegate = self
for i in 0..<sliderImagesArray.count {
var imageView : UIImageView
let xOrigin = self.imgScrollView.frame.size.width * CGFloat(i)
imageView = UIImageView(frame: CGRect(x: xOrigin, y: 0, width: self.imgScrollView.frame.size.width, height: self.imgScrollView.frame.size.height))
imageView.isUserInteractionEnabled = true
let urlStr = sliderImagesArray.object(at: i)
print(imgScrollView,imageView, urlStr)
imageView.sd_setImage(with: URL(string: urlStr as! String), placeholderImage: UIImage(named: "placeholder.png"))
imageView .contentMode = UIViewContentMode.scaleToFill
self.imgScrollView.addSubview(imageView)
}
self.imgScrollView.isPagingEnabled = true
self.imgScrollView.bounces = false
self.imgScrollView.showsVerticalScrollIndicator = false
self.imgScrollView.showsHorizontalScrollIndicator = false
self.imgScrollView.contentSize = CGSize(width:
self.imgScrollView.frame.size.width * CGFloat(sliderImagesArray.count), height: self.imgScrollView.frame.size.height)
imgPageController.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
self.imgPageController.numberOfPages = sliderImagesArray.count
self.imgPageController.currentPage = 0
self.imgPageController.tintColor = UIColor.red
self.imgPageController.pageIndicatorTintColor = UIColor.black
self.imgPageController.currentPageIndicatorTintColor = UIColor.blue
after that implement scrollview delegate methods
func changePage(sender: AnyObject) -> () {
let x = CGFloat(imgPageController.currentPage) * imgScrollView.frame.size.width
imgScrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(imgScrollView.contentOffset.x / imgScrollView.frame.size.width)
imgPageController.currentPage = Int(pageNumber)
}
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!
extension ZoomedPhotoViewController: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}
private 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
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}
private 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()
}
func scrollViewDidZoom(scrollView: UIScrollView) {
updateConstraintsForSize(view.bounds.size)
}
import UIKit
public class PhotoCommentViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var nameTextField: UITextField!
public var photoName: String!
override public func viewDidLoad() {
super.viewDidLoad()
if let photoName = photoName {
self.imageView.image = UIImage(named: photoName)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cell = sender as? UICollectionViewCell,
indexPath = collectionView?.indexPathForCell(cell),
photoCommentViewController = segue.destinationViewController as? PhotoCommentViewController {
photoCommentViewController.photoName = "photo\(indexPath.row + 1)"
}
}
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PhotoCommentViewController.keyboardWillShow(_:)),
name: UIKeyboardWillShowNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PhotoCommentViewController.keyboardWillHide(_:)),
name: UIKeyboardWillHideNotification,
object: nil
)
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return }
let keyboardFrame = value.CGRectValue()
let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 20) * (show ? 1 : -1)
scrollView.contentInset.bottom += adjustmentHeight
scrollView.scrollIndicatorInsets.bottom += adjustmentHeight
}
func keyboardWillShow(notification: NSNotification) {
adjustInsetForKeyboardShow(true, notification: notification)
}
func keyboardWillHide(notification: NSNotification) {
adjustInsetForKeyboardShow(false, notification: notification)
}
#IBAction func hideKeyboard(sender: AnyObject) {
nameTextField.endEditing(true)
}
public var photoIndex: Int!
import UIKit
class ManagePageViewController: UIPageViewController {
var photos = ["photo1", "photo2", "photo3", "photo4", "photo5"]
var currentIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
// 1
if let viewController = viewPhotoCommentController(currentIndex ?? 0) {
let viewControllers = [viewController]
// 2
setViewControllers(
viewControllers,
direction: .Forward,
animated: false,
completion: nil
)
}
}
func viewPhotoCommentController(index: Int) -> PhotoCommentViewController? {
if let storyboard = storyboard,
page = storyboard.instantiateViewControllerWithIdentifier("PhotoCommentViewController")
as? PhotoCommentViewController {
page.photoName = photos[index]
page.photoIndex = index
return page
}
return nil
}
}

Resources