What does margin is this? (PageMenu, swift, non-storyboard) - ios

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.

Related

CAPSPageMenu get the index when we press in menu taps

I have added a CAPSPageMenu. The current index is always 0.
I want to know the index of the menu item I tap on.
I tried below code but when I add the breakpoint to this delegate method it is not called.
I'm using this lib : https://github.com/PageMenu/PageMenu/blob/master/README.md
class firstVC: UIViewController,CAPSPageMenuDelegate {
var pageMenu : CAPSPageMenu?
override func viewDidLoad() {
super.viewDidLoad()
pageMenu?.delegate=self
}
func willMoveToPage(_ controller: UIViewController, index: Int){
print(index)
}
func didMoveToPage(_ controller: UIViewController, index: Int){
print(index)
}
}
Update :
#IBOutlet var optionView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
var menuTitleFont: UIFont?
if UIScreen.main.bounds.size.height == 568 {
menuTitleFont = UIFont(name: "roboto-Bold", size: 10.0)
}
else {
menuTitleFont = UIFont(name: "roboto-Bold", size: 12.0)
}
let parameters: [CAPSPageMenuOption] = [
.scrollMenuBackgroundColor(UIColor.yellow),
.viewBackgroundColor(UIColor.black),
.selectionIndicatorColor(UIColor.white),
.bottomMenuHairlineColor(UIColor.lightGray),
.selectedMenuItemLabelColor(UIColor.white),
.unselectedMenuItemLabelColor(UIColor.lightGray),
//.menuItemFont(12),
.menuHeight(50.0),
.menuItemWidth(self.view.frame.size.width/10 + 30),
.centerMenuItems(true)
]
print(pageMenu)
pageMenu!.delegate = self
var controllerArray = [UIViewController]()
if let AllVc = self.storyboard?.instantiateViewController(withIdentifier:"AllVc") {
AllVc.title = "AllVc"
controllerArray.append(AllVc)
}
if let baseVc = self.storyboard?.instantiateViewController(withIdentifier:"baseVc") {
baseVc.title = "baseVc"
controllerArray.append(baseVc)
}
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y:0.0, width:view.frame.width, height:self.view.frame.height), pageMenuOptions: parameters)
self.addChildViewController(pageMenu!)
self.optionView.addSubview(pageMenu!.view)
pageMenu!.didMove(toParentViewController: self)
}
this is my full viewdidload updated code.
You need to set the delegate after you initialise your CAPSPageMenu.
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y:0.0, width:view.frame.width, height:self.view.frame.height), pageMenuOptions: parameters)
pageMenu!.delegate = self
print(pageMenu)

UITabbar Image Not Updating

i want to update image of uitabbar programmatically but it's not updating when i update the image
looks duplicate ???
here is the answer i already tried but no success
UITabBarItem does not update image
UITabBar not showing selected item images in ios 7
how to programmatically change the tabbarItem's image
https://www.appcoda.com/ios-programming-how-to-customize-tab-bar-background-appearance/
Changing tab bar item image and text color iOS
okay now here is my code for customTabbar
// CustomTabBarViewController.swift
// CustomTabBar
import UIKit
class CustomTabBarViewController: UITabBarController, CustomTabBarDataSource, CustomTabBarDelegate, UITabBarControllerDelegate , UISearchBarDelegate, UISearchDisplayDelegate {
var searchController: UISearchController!
let searchBar = UISearchBar()
var btnBarBadge : MJBadgeBarButton!
var btnBar : MJBadgeBarButton!
// #IBOutlet weak var menuButton: UIBarButtonItem!
// MARK: Properties
var meals = [CatModel]()
func onBagdeButtonClick() {
print("button Clicked \(self.btnBarBadge.badgeValue)")
}
func onBarCodeButtonClick() {
self.title = Localization("Categories")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let subContentsVC = storyboard.instantiateViewController(withIdentifier: "Stores") as! Stores
self.navigationController?.pushViewController(subContentsVC, animated: true)
}
func buttonClicked(_ sender: AnyObject?) {
var countt = Int(Constants.cartCount)
if(countt == nil){
countt = 0
}
if(countt!<1){
let alert = UIAlertController(title: Localization("Warning"), message:Localization("YourCartisEmpty"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localization("Ok"), style: .default) { _ in })
self.present(alert, animated: true){}
}else{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let subContentsVC = storyboard.instantiateViewController(withIdentifier: "Cart") as! Cart
self.navigationController?.pushViewController(subContentsVC, animated: true)
}
}
func searchBarSearchButtonClicked( _ searchBar: UISearchBar)
{
print(searchBar.text ?? "this is value")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let subContentsVC = storyboard.instantiateViewController(withIdentifier: "SearchProduct") as! SearchProduct
subContentsVC.stringPassed = searchBar.text!
self.navigationController?.pushViewController(subContentsVC, animated: true)
}
func actOnSpecialNotificationon() {
searchBar.placeholder = Localization("Search")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tabBar.isHidden = true
self.selectedIndex = 1
self.delegate = self
searchBar.sizeToFit()
searchBar.delegate = self
self.title = Localization("Categories")
searchBar.placeholder = Localization("Search")
searchBar.tintColor = .black
navigationItem.titleView = searchBar
NotificationCenter.default.addObserver(self, selector: #selector(CustomTabBarViewController.actOnSpecialNotificationon), name: NSNotification.Name(rawValue: mySpecialNotificationKey), object: nil)
let customTabBar = CustomTabBar(frame: self.tabBar.frame)
customTabBar.datasource = self
customTabBar.delegate = self
customTabBar.setup()
self.view.addSubview(customTabBar)
let customButton = UIButton(type: UIButtonType.custom)
customButton.frame = CGRect(x: 0, y: 0, width: 5.0, height: 35.0)
customButton.addTarget(self, action: #selector(self.onBagdeButtonClick), for: .touchUpInside)
customButton.setImage(UIImage(named: "Cart"), for: .normal)
let barcodeButton = UIButton(type: UIButtonType.custom)
barcodeButton.frame = CGRect(x: 0, y: 0, width: 35.0, height: 35.0)
barcodeButton.addTarget(self, action: #selector(self.onBarCodeButtonClick), for: .touchUpInside)
barcodeButton.setImage(UIImage(named: "edit_location"), for: .normal)
self.btnBarBadge = MJBadgeBarButton()
self.btnBar = MJBadgeBarButton()
self.btnBarBadge.setup(customButton: customButton)
self.btnBarBadge.removeBadge()
self.btnBar.setup(customButton: barcodeButton)
self.btnBar.removeBadge()
self.btnBarBadge.badgeValue = "0"
self.btnBarBadge.badgeOriginX = 2.0
self.btnBarBadge.badgeOriginY = -4
self.navigationItem.rightBarButtonItem = self.btnBarBadge
self.navigationItem.rightBarButtonItems = [self.btnBarBadge,self.btnBar]
customButton.addTarget(self, action: #selector(CustomTabBarViewController.buttonClicked(_:)), for: .touchUpInside)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
self.btnBarBadge.badgeValue = Constants.cartCount
}
// MARK: - CustomTabBarDataSource
func tabBarItemsInCustomTabBar(_ tabBarView: CustomTabBar) -> [UITabBarItem] {
return tabBar.items!
}
// MARK: - CustomTabBarDelegate
func didSelectViewController(_ tabBarView: CustomTabBar, atIndex index: Int) {
if(index == 0){
self.openLeftMenu()
}else{
self.selectedIndex = index
}
for loop in 0..<(self.tabBar.items?.count)!{
let barbutton = self.tabBar.items![loop]
if(index == loop){
barbutton.image = self.updateImageColor(origImage: barbutton.image!, color: .green)
}else{
barbutton.image = self.updateImageColor(origImage: barbutton.image!, color: .lightGray)
}
}
}
func updateImageColor(origImage:UIImage,color:UIColor)->UIImage{
let tintedImage = origImage.withRenderingMode(.alwaysOriginal)
let imageview = UIImageView(image: tintedImage)
imageview.tintColor = color
return imageview.image!
}
// MARK: - UITabBarControllerDelegate
func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CustomTabAnimatedTransitioning()
}
}
here is the code for CustomTabBar.swift
//
// CustomTabBar.swift
// CustomTabBar
//
import UIKit
protocol CustomTabBarDataSource {
func tabBarItemsInCustomTabBar(_ tabBarView: CustomTabBar) -> [UITabBarItem]
}
protocol CustomTabBarDelegate {
func didSelectViewController(_ tabBarView: CustomTabBar, atIndex index: Int)
}
class CustomTabBar: UIView {
var datasource: CustomTabBarDataSource!
var delegate: CustomTabBarDelegate!
var tabBarItems: [UITabBarItem]!
var customTabBarItems: [CustomTabBarItem]!
var tabBarButtons: [UIButton]!
var initialTabBarItemIndex: Int!
var selectedTabBarItemIndex: Int!
var slideMaskDelay: Double!
var slideAnimationDuration: Double!
var tabBarItemWidth: CGFloat!
var leftMask: UIView!
var rightMask: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
// get tab bar items from default tab bar
tabBarItems = datasource.tabBarItemsInCustomTabBar(self)
customTabBarItems = []
tabBarButtons = []
initialTabBarItemIndex = 1
selectedTabBarItemIndex = initialTabBarItemIndex
slideAnimationDuration = 0.6
slideMaskDelay = slideAnimationDuration / 2
let containers = createTabBarItemContainers()
createTabBarItemSelectionOverlay(containers)
createTabBarItemSelectionOverlayMask(containers)
createTabBarItems(containers)
}
func createTabBarItemSelectionOverlay(_ containers: [CGRect]) {
let activeColor = UIColor(red: 109/255, green: 187/255, blue: 16/255, alpha: 1.0)
let overlayColors = [activeColor, activeColor, activeColor, activeColor,activeColor]
for index in 0..<tabBarItems.count {
let container = containers[index]
let view = UIView(frame: container)
let selectedItemOverlay = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
selectedItemOverlay.backgroundColor = overlayColors[index] //.clear
view.addSubview(selectedItemOverlay)
tabBarItems[index].selectedImage = updateImageColor(origImage: tabBarItems[index].image!, color: .green)
self.addSubview(view)
}
}
func updateImageColor(origImage:UIImage,color:UIColor)->UIImage{
let tintedImage = origImage.withRenderingMode(.alwaysTemplate)
let imageview = UIImageView(image: tintedImage)
imageview.tintColor = color
return imageview.image!
}
func createTabBarItemSelectionOverlayMask(_ containers: [CGRect]) {
tabBarItemWidth = self.frame.width / CGFloat(tabBarItems.count)
let leftOverlaySlidingMultiplier = CGFloat(initialTabBarItemIndex) * tabBarItemWidth
let rightOverlaySlidingMultiplier = CGFloat(initialTabBarItemIndex + 1) * tabBarItemWidth
leftMask = UIView(frame: CGRect(x: 0, y: 0, width: leftOverlaySlidingMultiplier, height: self.frame.height))
leftMask.backgroundColor = UIColor.white
rightMask = UIView(frame: CGRect(x: rightOverlaySlidingMultiplier, y: 0, width: tabBarItemWidth * CGFloat(tabBarItems.count - 1), height: self.frame.height))
rightMask.backgroundColor = UIColor.white
self.addSubview(leftMask)
self.addSubview(rightMask)
}
func createTabBarItems(_ containers: [CGRect]) {
var index = 0
for item in tabBarItems {
let container = containers[index]
let customTabBarItem = CustomTabBarItem(frame: container)
customTabBarItem.setup(item)
self.addSubview(customTabBarItem)
customTabBarItems.append(customTabBarItem)
let button = UIButton(frame: CGRect(x: 0, y: 0, width: container.width, height: container.height))
button.addTarget(self, action: #selector(CustomTabBar.barItemTapped(_:)), for: UIControlEvents.touchUpInside)
customTabBarItem.addSubview(button)
tabBarButtons.append(button)
index += 1
}
self.customTabBarItems[initialTabBarItemIndex].iconView.tintColor = .green //UIColor.white
}
func createTabBarItemContainers() -> [CGRect] {
var containerArray = [CGRect]()
// create container for each tab bar item
for index in 0..<tabBarItems.count {
let tabBarContainer = createTabBarContainer(index)
containerArray.append(tabBarContainer)
}
return containerArray
}
func createTabBarContainer(_ index: Int) -> CGRect {
let tabBarContainerWidth = self.frame.width / CGFloat(tabBarItems.count)
let tabBarContainerRect = CGRect(x: tabBarContainerWidth * CGFloat(index), y: 0, width: tabBarContainerWidth, height: self.frame.height)
return tabBarContainerRect
}
func animateTabBarSelection(from: Int, to: Int) {
let overlaySlidingMultiplier = CGFloat(to - from) * tabBarItemWidth
let leftMaskDelay: Double
let rightMaskDelay: Double
if overlaySlidingMultiplier > 0 {
leftMaskDelay = slideMaskDelay
rightMaskDelay = 0
}
else {
leftMaskDelay = 0
rightMaskDelay = slideMaskDelay
}
UIView.animate(withDuration: slideAnimationDuration - leftMaskDelay, delay: leftMaskDelay, options: UIViewAnimationOptions(), animations: {
self.leftMask.frame.size.width += overlaySlidingMultiplier
}, completion: nil)
UIView.animate(withDuration: slideAnimationDuration - rightMaskDelay, delay: rightMaskDelay, options: UIViewAnimationOptions(), animations: {
self.rightMask.frame.origin.x += overlaySlidingMultiplier
self.rightMask.frame.size.width += -overlaySlidingMultiplier
self.customTabBarItems[from].iconView.tintColor = UIColor.black
self.customTabBarItems[to].iconView.tintColor = UIColor.white
}, completion: nil)
}
func barItemTapped(_ sender : UIButton) {
let index = tabBarButtons.index(of: sender)!
//tabBarItems[index].selectedImage = nil
//tabBarItems[index].image = nil
// tabBarItems[index].image = UIImage(named: "Home_Tab");
animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
selectedTabBarItemIndex = index
delegate.didSelectViewController(self, atIndex: index)
}
}
when i try changing image nothing happen
tabBarItems[index].image = UIImage(named: "Home_Tab")
tabBarItems[index].image = UIImage(named: "Home_Tab")?.withRenderingMode(.alwaysOriginal)
Same for selected image
it works when i set image in createTabBarItemSelectionOverlay method
i tried removing image and setting it again but no success
also tried to set image with .alwaysOriginal render mode no luck
please help where am i doing wrong ??
Thank you...little help will be appriciated

UIView gradient background is not getting set

I have a UIViewController that is also a UIScrollViewDelegate
The UIViewController has multiple slides that are UIViews and for each slide I want to set a different gradient background color programmatically, however it does not seem to be working as no gradient is being set.
My UIView extension
import UIKit
extension UIView {
func addGradient(){
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [UIColor.black, UIColor.orange]
let backgroundIndex:UInt32 = 0;
self.layer.insertSublayer(gradient, at: backgroundIndex)
}
}
My FirstSlide that has it's own FirstSlide.xib
import UIKit
class FirstSlide: UIView {
}
In my WelcomeSliderViewController
import UIKit
class WelcomeSliderViewController: UIViewController, UIScrollViewDelegate{
#IBOutlet weak var slideScrollView: UIScrollView!
#IBOutlet weak var pagerControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
slideScrollView.delegate = self
let slides = createSlides()
setupSliderView(slides: slides)
pagerControl.numberOfPages = slides.count
pagerControl.currentPage = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func pagerControlClicked(_ sender: Any) {
self.slideScrollView
.scrollRectToVisible(CGRect(
x: Int(self.slideScrollView.frame.size.width) * self.pagerControl.currentPage,
y: 0,
width:Int(self.slideScrollView.frame.size.width),
height: Int(self.slideScrollView.frame.size.height)),
animated: true)
}
func createSlides() -> [UIView] {
let firstSlide: FirstSlide = Bundle.main.loadNibNamed("FirstSlide", owner:self , options: nil)?.first as! FirstSlide
let secondSlide: SecondSlide = Bundle.main.loadNibNamed("SecondSlide", owner:self , options: nil)?.first as! SecondSlide
firstSlide.addGradient()
return [firstSlide, SecondSlide]
}
func setupSliderView(slides:[UIView]) {
slideScrollView.frame = CGRect(x: 0, y:0, width: view.frame.width, height: view.frame.height)
slideScrollView.contentSize = CGSize(width: view.frame.width * CGFloat(slides.count), height: view.frame.height)
for i in 0 ..< slides.count{
slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
slideScrollView.addSubview(slides[i])
}
}
func scrollViewDidEndDecelerating(_ scrollView : UIScrollView){
let pageIndex = round(scrollView.contentOffset.x / view.frame.width)
pagerControl.currentPage = Int(pageIndex)
}
}
It's not working because you are passing UIColors instead of CGColors in the .colors Array of the CAGradientLayer.
It should be like this:
func addGradient(){
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [UIColor.black.cgColor, UIColor.orange.cgColor]
let backgroundIndex:UInt32 = 0;
self.layer.insertSublayer(gradient, at: backgroundIndex)
}

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
}
}

ViewController does not conform to protocol on Swift

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).

Resources