I'm having an issue with calling a delegate in my class. I have a SideBarTableController and SideBar.swift file.It was working fine until I logged off and back in. Here is the code. It keeps telling me that 'ViewController' does not conform to protocol 'SideBarDelegate'. I'm new to programming so sorry in advance if this is vague. Anything will help thanks!
import UIKit
import iAd
class ViewController: UIViewController, SideBarDelegate { -----This is where the error is happening
#IBOutlet var menuTab: UIButton! // Menu Tab
#IBOutlet var businessButton: UIButton! // Business Button
#IBOutlet var adBanner: ADBannerView! // Banner Ad
#IBOutlet var imageView: UIImageView! // Main Image in middle
var topHeader: UIImageView! // Utility header
var sideBar:SideBar = SideBar() // Side Bar
override func viewDidLoad() {
super.viewDidLoad()
// Function for menu
// menuTab.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)
func menuTab(sender: UIButton){
sideBar = SideBar(sourceView: self.view, menuItems: ["Home", "Business Directory", "Classifieds", "Featured News", "Jobs", "Restaurants", "Sports"])
sideBar.delegate = self }
// Gives the screen dimensions
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
// Side bar action and text
sideBar = SideBar(sourceView: self.view, menuItems: ["Home", "Business Directory", "Classifieds", "Featured News", "Jobs", "Restaurants", "Sports"])
sideBar.delegate = self
// Utility Background
var topHeader = UIView(frame: CGRectMake(0, 0, screenWidth, 17))
topHeader.backgroundColor = UIColor(white: 0.0, alpha: 1.0)
self.view.addSubview(topHeader)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Side Bar funcion
func sideBarDidSelectButtonAtIndex(index: Int) {
if index == 0{
imageView.backgroundColor = UIColor.redColor()
imageView.image = nil
} else if index == 1{
imageView.backgroundColor = UIColor.clearColor()
imageView.image = UIImage(named: "image2")
}
}
// Status bar style (white)
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
Here is where I called the SideBarDelegate
import UIKit
#objc protocol SideBarDelegate{
func sideBarDidSelectButtonAtIndex(index:Int)
func sideBarWillClose()
func sideBarWillOpen()
}
class SideBar: NSObject, SideBarTableViewControllerDelegate {
let barWidth:CGFloat = 176.0
let sideBarTableViewTopInset:CGFloat = 64.0
let sideBarContainerView:UIView = UIView()
let sideBarTableViewController:SideBarTableViewController = SideBarTableViewController()
let originView:UIView!
var animator:UIDynamicAnimator!
var delegate:SideBarDelegate?
var isSideBarOpen:Bool = false
override init() {
super.init()
}
init(sourceView:UIView, menuItems:Array<String>){
super.init()
originView = sourceView
sideBarTableViewController.tableData = menuItems
setupSideBar()
animator = UIDynamicAnimator(referenceView: originView)
let showGestureRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
showGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
originView.addGestureRecognizer(showGestureRecognizer)
let hideGestureRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
hideGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
originView.addGestureRecognizer(hideGestureRecognizer)
}
func setupSideBar(){
sideBarContainerView.frame = CGRectMake(-barWidth - 1, originView.frame.origin.y, barWidth, originView.frame.size.height)
sideBarContainerView.backgroundColor = UIColor.clearColor()
sideBarContainerView.clipsToBounds = false
originView.addSubview(sideBarContainerView)
let blurView:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
blurView.frame = sideBarContainerView.bounds
sideBarContainerView.addSubview(blurView)
sideBarTableViewController.delegate = self
sideBarTableViewController.tableView.frame = sideBarContainerView.bounds
sideBarTableViewController.tableView.clipsToBounds = false
sideBarTableViewController.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
sideBarTableViewController.tableView.backgroundColor = UIColor.clearColor()
sideBarTableViewController.tableView.scrollsToTop = false
sideBarTableViewController.tableView.contentInset = UIEdgeInsetsMake(sideBarTableViewTopInset, 0, 0, 0)
sideBarTableViewController.tableView.reloadData()
sideBarContainerView.addSubview(sideBarTableViewController.tableView)
}
func handleSwipe(recognizer:UISwipeGestureRecognizer){
if recognizer.direction == UISwipeGestureRecognizerDirection.Left{
showSideBar(false)
delegate?.sideBarWillClose()
}else{
showSideBar(true)
delegate?.sideBarWillOpen()
}
}
func showSideBar(shouldOpen:Bool){
animator.removeAllBehaviors()
isSideBarOpen = shouldOpen
let gravityX:CGFloat = (shouldOpen) ? 0.5 : -0.5
let magnitude:CGFloat = (shouldOpen) ? 20 : -20
let boundaryX:CGFloat = (shouldOpen) ? barWidth : -barWidth - 1
let gravityBehavior:UIGravityBehavior = UIGravityBehavior(items: [sideBarContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior:UICollisionBehavior = UICollisionBehavior(items: [sideBarContainerView])
collisionBehavior.addBoundaryWithIdentifier("sideBarBoundary", fromPoint: CGPointMake(boundaryX, 20), toPoint: CGPointMake(boundaryX, originView.frame.size.height))
animator.addBehavior(collisionBehavior)
let pushBehavior:UIPushBehavior = UIPushBehavior(items: [sideBarContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = magnitude
animator.addBehavior(pushBehavior)
let sideBarBehavior:UIDynamicItemBehavior = UIDynamicItemBehavior(items: [sideBarContainerView])
sideBarBehavior.elasticity = 0.3
animator.addBehavior(sideBarBehavior)
}
func sideBarControlDidSelectRow(indexPath: NSIndexPath) {
delegate?.sideBarDidSelectButtonAtIndex(indexPath.row)
}
}
Your SideBarDelegate protocol specifies some methods that must be implemented in order to conform to that protocol. So look at the definition of that protocol, identify what methods are defined therein, and then implement them in your ViewController class.
It's possible you missed one of the functions defined in that protocol, or perhaps you mistyped something in the definition of sideBarDidSelectButtonAtIndex. We cannot say without seeing the definition of this protocol.
Update:
You subsequently supplied the definition of your protocol. It defines two additional functions that you have not implemented in your view controller:
func sideBarWillClose()
func sideBarWillOpen()
You also must implement these two functions in your view controller (even if you put nothing into them).
Related
simulator ScreenShot
I have used PageMenu Library.
I have used swift and not story-board.
https://github.com/HighBay/PageMenu
How do I remove this margin ?
The following is source code.
ProjectDetailViewController.swift
class ProjectDetailViewController : UIViewController, CAPSPageMenuDelegate{
var projectId:NSInteger!
var firstView: FirstViewController!
var secondView: SecondViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.title = "PageMenu"
firstView = FirstViewController()
secondView = SecondViewController()
firstView.title = "test1"
secondView.title = "test2"
var controllerArray : [UIViewController] = []
controllerArray.append(firstView)
controllerArray.append(secondView)
let parameters: [CAPSPageMenuOption] = [
.MenuItemSeparatorWidth(0.0),
.UseMenuLikeSegmentedControl(true),
.MenuItemSeparatorPercentageHeight(0.0),
.SelectedMenuItemLabelColor(UIColor.hex("#ffee58", alpha: 1)),
.ScrollMenuBackgroundColor(UIColor.hex("#fffde7", alpha: 1)),
.SelectionIndicatorColor(UIColor.hex("#ffee58", alpha: 1)),
]
let topMargin:CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height+self.navigationController!.navigationBar.frame.size.height;
let pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, topMargin, self.view.frame.width, self.view.frame.height-topMargin), pageMenuOptions: parameters)
pageMenu.delegate = self
self.addChildViewController(pageMenu)
self.view.addSubview(pageMenu.view)
pageMenu.didMoveToParentViewController(self)
}
func willMoveToPage(controller: UIViewController, index: Int){
NSLog("willMoveToPage");
}
func didMoveToPage(controller: UIViewController, index: Int){
NSLog("didMoveToPage");
}
}
FirstViewController.swift
class FirstViewController:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSLog("x = %f y = %f width = %f height = %f", self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)
self.view.backgroundColor = UIColor.blueColor()
}
}
SecondViewController.swift
class SecondViewController:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.greenColor()
}
}
thanks.
I want to swipe each image to switch to another image like gallery app. I am now using this https://github.com/nicklockwood/SwipeView, but I don't know how to implement it. Should I drag a collection view inside my PhotoDetailViewController, or I only use it in coding. May anyone help me with this.
Here is my code:
import Foundation
import UIKit
import AAShareBubbles
import SwipeView
class PhotoDetailViewController: UIViewController, AAShareBubblesDelegate, SwipeViewDataSource, SwipeViewDelegate {
#IBOutlet var topView: UIView!
#IBOutlet var bottomView: UIView!
#IBOutlet var photoImageView: UIImageView!
var photoImage = UIImage()
var checkTapGestureRecognize = true
var swipeView: SwipeView = SwipeView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height))
override func viewDidLoad() {
title = "Photo Detail"
super.viewDidLoad()
photoImageView.image = photoImage
swipeView.dataSource = self
swipeView.delegate = self
let swipe = UISwipeGestureRecognizer(target: self, action: "swipeMethod")
swipeView.addGestureRecognizer(swipe)
swipeView.addSubview(photoImageView)
swipeView.pagingEnabled = false
swipeView.wrapEnabled = true
}
func swipeView(swipeView: SwipeView!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! {
return photoImageView
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SwipeCell", forIndexPath: indexPath) as! SwipeViewPhotoCell
return cell
}
#IBAction func onBackClicked(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
#IBAction func onTabGestureRecognize(sender: UITapGestureRecognizer) {
print("on tap")
if checkTapGestureRecognize == true {
bottomView.hidden = true
topView.hidden = true
self.navigationController?.navigationBarHidden = true
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
photoImageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
checkTapGestureRecognize = false
showAminationOnAdvert()
}
else if checkTapGestureRecognize == false {
bottomView.hidden = false
topView.hidden = false
self.navigationController?.navigationBarHidden = false
checkTapGestureRecognize = true
}
}
func showAminationOnAdvert() {
let transitionAnimation = CATransition();
transitionAnimation.type = kCAEmitterBehaviorValueOverLife
transitionAnimation.subtype = kCAEmitterBehaviorValueOverLife
transitionAnimation.duration = 2.5
transitionAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transitionAnimation.fillMode = kCAFillModeBoth
photoImageView.layer.addAnimation(transitionAnimation, forKey: "fadeAnimation")
}
#IBAction func onShareTouched(sender: AnyObject) {
print("share")
let myShare = "I am feeling *** today"
let shareVC: UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil)
self.presentViewController(shareVC, animated: true, completion: nil)
// print("share bubles")
// let shareBubles: AAShareBubbles = AAShareBubbles.init(centeredInWindowWithRadius: 100)
// shareBubles.delegate = self
// shareBubles.bubbleRadius = 40
// shareBubles.sizeToFit()
// //shareBubles.showFacebookBubble = true
// shareBubles.showTwitterBubble = true
// shareBubles.addCustomButtonWithIcon(UIImage(named: "twitter"), backgroundColor: UIColor.whiteColor(), andButtonId: 100)
// shareBubles.show()
}
#IBAction func playAutomaticPhotoImages(sender: AnyObject) {
animateImages(0)
}
func animateImages(no: Int) {
var number: Int = no
if number == images.count - 1 {
number = 0
}
let name: String = images[number]
self.photoImageView!.alpha = 0.5
self.photoImageView!.image = UIImage(named: name)
//code to animate bg with delay 2 and after completion it recursively calling animateImage method
UIView.animateWithDuration(2.0, delay: 0.8, options:UIViewAnimationOptions.CurveEaseInOut, animations: {() in
self.photoImageView!.alpha = 1.0;
},
completion: {(Bool) in
number++;
self.animateImages(number);
print(String(images[number]))
})
}
}
Just drag and drop a UIView to your storyboard/XIB, and set its customclass to SwipeView.
Also set the delegate and datasource to the view controller which includes the UIView you just dragged.
Then in the viewcontroller, implement the required delegate methods similar to how you'd implement the methods for a tableview.
I currently have a menu (SideBar) that reveals upon swipe and I want the menu to slide from right to left. I changed the swipe direction to match but I'm not sure how to change the SideBar frame or animation. How can I make the SideBar come from the right instead of left?
//
// SideBar.swift
// SideBarMenu
//
// Created by Alexandre on 30/01/2015.
// Copyright (c) 2015 Alexandre. All rights reserved.
//
import UIKit
//Necessary if we want to specify orptional requirements
#objc protocol SideBarDelegate{
func sideBarDidSelectButtonAtIndex(index:Int)
optional func sideBarWillClose()
optional func sideBarWillOpen()
}
//When an item of the sidebar is selected, and also when the sidebar will open or close
class SideBar: NSObject, SideBarTableViewControllerDelegate {
let barWidth:CGFloat = 150.0
let sideBarTableViewTopInset:CGFloat = 64.0
let sideBarContainerView:UIView = UIView()
let sideBarTableViewController:SideBarTableViewController = SideBarTableViewController()
var originView:UIView!
var animator:UIDynamicAnimator!
var delegate:SideBarDelegate!
var isSideBarOpen:Bool = false
//This init only allocate memory
override init(){
super.init()
}
init(sourceView:UIView, menuItems:Array<String>){
super.init()
originView = sourceView
sideBarTableViewController.tableData = menuItems
setupSideBar()
animator = UIDynamicAnimator(referenceView: originView)
let showGestureRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
showGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
originView.addGestureRecognizer(showGestureRecognizer)
let hideGestureRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
hideGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
originView.addGestureRecognizer(hideGestureRecognizer)
}
func setupSideBar(){
sideBarContainerView.frame = CGRectMake(-barWidth - 1, originView.frame.origin.y, barWidth, originView.frame.size.height)
sideBarContainerView.backgroundColor = UIColor.clearColor()
sideBarContainerView.clipsToBounds = false
//Add the sideBar to the originView
originView.addSubview(sideBarContainerView)
//blur back of the ground
//let blurView:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
//blurView.frame = sideBarContainerView.bounds
//sideBarContainerView.addSubview(blurView)
//Setup the menu/tableView
sideBarTableViewController.delegate = self
sideBarTableViewController.tableView.frame = sideBarContainerView.bounds
sideBarTableViewController.tableView.clipsToBounds = false
sideBarTableViewController.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
sideBarTableViewController.tableView.backgroundColor = UIColor.clearColor()
sideBarTableViewController.tableView.scrollsToTop = false
sideBarTableViewController.tableView.contentInset = UIEdgeInsetsMake(sideBarTableViewTopInset, 0, 0, 0)
sideBarTableViewController.tableView.reloadData()
sideBarContainerView.addSubview(sideBarTableViewController.tableView)
}
func handleSwipe(recognizer:UISwipeGestureRecognizer){
if recognizer.direction == UISwipeGestureRecognizerDirection.Right {
showSideBar(false)
delegate?.sideBarWillClose?()
} else {
showSideBar(true)
delegate?.sideBarWillOpen?()
}
}
func showSideBar(shouldOpen:Bool){
animator.removeAllBehaviors()
isSideBarOpen = shouldOpen
//The gravity modifies the open and close speed
let gravityX:CGFloat = (shouldOpen) ? 1 : -1
let magnitude:CGFloat = (shouldOpen) ? 20 : -20
let boundaryX:CGFloat = (shouldOpen) ? barWidth : -barWidth - 1
let gravity:UIGravityBehavior = UIGravityBehavior(items: [sideBarContainerView])
gravity.gravityDirection = CGVectorMake(gravityX, 0)
animator.addBehavior(gravity)
let collisionBehavior:UICollisionBehavior = UICollisionBehavior(items: [sideBarContainerView])
collisionBehavior.addBoundaryWithIdentifier("sideBarBoundary", fromPoint: CGPointMake(boundaryX, 20), toPoint: CGPointMake(boundaryX, originView.frame.size.height))
animator.addBehavior(collisionBehavior)
let pushBehavior:UIPushBehavior = UIPushBehavior(items: [sideBarContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = magnitude
animator.addBehavior(pushBehavior)
let sideBarBehavior:UIDynamicItemBehavior = UIDynamicItemBehavior(items: [sideBarContainerView])
sideBarBehavior.elasticity = -0.3
animator.addBehavior(sideBarBehavior)
}
func sideBarControlDidSelectRow(indexPath: NSIndexPath) {
delegate?.sideBarDidSelectButtonAtIndex(indexPath.row)
}
}
What you want to do is make your starting frame offscreen to the right instead of the left. You'll also need to change the gravity direction.
in setupSideBar, you'll want to change the first line:
sideBarContainerView.frame = CGRectMake(barWidth + 1, originView.frame.origin.y, barWidth, originView.frame.size.height)
// notice the change in the first value (x position)
// the width +1 puts it offscreen +1.
// Previously it was -width-1 which put it to the left
then, in showSideBar:
// just reversing the gravity
let gravityX:CGFloat = (shouldOpen) ? -1 : 1
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
}
}
I would like to create a simple flip effect, but I don't understand the problems I have here :
the whole screen is flipping, not only the view, is there a way to flip the 100,100 square only?
I can only flip twice, then the tap does not work anymore, would you know why?
import UIKit
class ViewController: UIViewController {
var fromOneToTwo : Bool = true
var view1 : UIImageView!
var view2 : UIImageView!
var tap : UITapGestureRecognizer!
func handleTap(tap: UITapGestureRecognizer){
println("1/fromOneToTwo \(fromOneToTwo)")
var v1 = (fromOneToTwo ? self.view1 : self.view2)
var v2 = (fromOneToTwo ? self.view2 : self.view1)
UIView.transitionFromView(v1, toView: v2, duration: 0.5, options: (UIViewAnimationOptions.TransitionFlipFromLeft | UIViewAnimationOptions.CurveEaseInOut) ) { finished in
self.fromOneToTwo = !self.fromOneToTwo
println("2/fromOneToTwo \(self.fromOneToTwo) ")
}
}
func createView( str:String)->UIImageView!{
var img = UIImage(named: str)!
var imgView = UIImageView(frame: CGRectMake(0,0, 200, 200))
imgView.image = img
imgView.sizeToFit()
imgView.userInteractionEnabled = true
imgView.addGestureRecognizer(tap)
return imgView
}
required init(coder aDecoder:NSCoder){
super.init(coder:aDecoder)
tap = UITapGestureRecognizer(target: self, action: "handleTap:")
view1 = createView("imageOnee.png")
view2 = createView("imageTwo.png")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(view1)
view.addSubview(view2)
view.backgroundColor = UIColor.redColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Also, when I try to add the whole code in a custom UIView, and add the custom instance myViewto the ViewController, the tap does not work at all.
I made this work creating a container view for view1 and view2. The tap recognizer is then added to this container view.
class ViewController: UIViewController {
var fromOneToTwo : Bool = true
var view1 : UIImageView!
var view2 : UIImageView!
var container : UIView!
var tap : UITapGestureRecognizer!
func handleTap(tap: UITapGestureRecognizer){
println("1/fromOneToTwo \(fromOneToTwo)")
var v1 = (fromOneToTwo ? self.view1 : self.view2)
var v2 = (fromOneToTwo ? self.view2 : self.view1)
UIView.transitionFromView(v1, toView: v2, duration: 0.5, options: .TransitionFlipFromLeft | .CurveEaseInOut ) { finished in
self.fromOneToTwo = !self.fromOneToTwo
println("2/fromOneToTwo \(self.fromOneToTwo) ")
}
}
func createView( str:String)->UIImageView!{
var img = UIImage(named: str)!
var imgView = UIImageView(frame: CGRectMake(0, 0, 200, 200))
imgView.image = img
imgView.sizeToFit()
return imgView
}
required init(coder aDecoder:NSCoder){
super.init(coder:aDecoder)
tap = UITapGestureRecognizer(target: self, action: "handleTap:")
view1 = createView("imageOnee.png")
container = UIView(frame: CGRectMake(0, 0, view1.bounds.width, view1.bounds.height))
container.userInteractionEnabled = true
container.addGestureRecognizer(tap)
container.addSubview(view1)
view2 = createView("imageTwo.png")
container.addSubview(view2)
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(container)
view.backgroundColor = UIColor.redColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}