Swift and Xcode - How to Create Custom Tab Bar Icons - ios

I have a tabbed application project I am working on in Xcode written in Swift (Xcode 6.3 and Swift 1.2). I am having a lot of trouble with custom Tab Bar icons. I have designed an image in Photoshop (CS6), saved it as a PNG, resized it in Prepo to be 30x30 and imported it into Xcode in the asset library. I then set the tab view controllers icon to that image. However, it doesn't show up.
I have looked at these pages but not found any help:
https://www.youtube.com/watch?v=4qqqoAWNfZA
Custom tab bar icon colors
http://www.raywenderlich.com/forums/viewtopic.php?f=2&t=19333
http://www.appcoda.com/ios-programming-how-to-customize-tab-bar-background-appearance/
https://www.youtube.com/watch?v=4Tj_SeApUrs
What is the proper process to create custom tab bar icons?

After a bit of research I resolved the issue, so thought I'd post here in case anyone else has a similar issue. In Photoshop I did the following:
Imported the image I wanted to use as the tab bar icon (its easier if you use a black and white image so that you don't have to remove colour).
Set the background to 'Transparent' rather than white.
Removed all white from the image so that it was just a black image with a transparent background.
Saved the image as a .png.
Resized the image to be a square with dimensions 75x75 pixels (and named imageName#3x.png), 50x50 pixels (and named imageName#2x.png), and 25x25 pixels (and named imageName.png)
In Xcode I did the following:
Dragged the images into Xcode and renamed the image group as icoImageName.
Selected the tab I wanted to set the image for in the storyboard in Xcode and set the 'Image' (under 'Bar Item' in the Inspector Pane) to icoImageName. Note that I did not set the 'Selected Image' under the 'Tab Bar Item' (leave this blank).
Done.
I hope this helps someone. Thanks to everyone for their help as well.

It sounds like you have everything set up properly in xCode. The problem IS the png file you are using.
Download this image, http://i.stack.imgur.com/zluev.png , and see if the problem persists.
According to an answer on UITabBarItem images just appear as a grey block:
The standard tabbar icons in iOS are rendered solely from the alpha channel. Colors are ignored completely. Instead of colors you can use different alpha values that lead to a different shade of gray (or blue if selected)
Make the background of your icons transparent.

Did you create the tab view in interface builder? If so, since you added the images as an asset they should show up in the 'Image' property of each tab button under the inspector sidebar. Also, I know you've already posted a ton of tutorials, but this one is pretty up to date and explains it thoroughly: http://codewithchris.com/ios-tab-bar-app/

class ViewController: UIViewController {
#IBOutlet var btnHome : UIButton!
#IBOutlet var btnInvoice : UIButton!
#IBOutlet var btnSettings : UIButton!
#IBOutlet var btnMyOrder : UIButton!
#IBOutlet var btnLogout : UIButton!
#IBOutlet weak var viewContainer: UIView!
var navController : UINavigationController!
var selectedIndex : Int! = 0
var arrTabColor = [UIColor(red: 35.0/255.0, green: 93.0/255.0, blue: 175.0/255.0, alpha: 1.0),
UIColor(red: 29.0/255.0, green: 86.0/255.0, blue: 167.0/255.0, alpha: 1.0),
UIColor(red: 35.0/255.0, green: 93.0/255.0, blue: 175.0/255.0, alpha: 1.0),
UIColor(red: 29.0/255.0, green: 86.0/255.0, blue: 167.0/255.0, alpha: 1.0),
UIColor(red: 35.0/255.0, green: 93.0/255.0, blue: 175.0/255.0, alpha: 1.0)]
var arrTabIdentiFierVC = ["FirstVC","SecondVC","FirstVC","FirstVC","SecondVC"]
// MARK: - Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
setTabbarImage(0)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setTabBarClicked(_ storyIdentifier : String,identifier : String)
{
let aStoryboard = UIStoryboard.init(name: storyIdentifier, bundle: nil)
let newViewController = aStoryboard.instantiateViewController(withIdentifier: identifier)
navController = UINavigationController(rootViewController: newViewController)
self.addChildViewController(navController)
navController.view.frame = viewContainer.frame
newViewController.view.frame = viewContainer.frame
self.viewContainer.addSubview(navController.view)
newViewController.didMove(toParentViewController: self)
}
func setTabbarImage(_ selectedIndex : Int!)
{
btnHome.backgroundColor = arrTabColor[0]
btnInvoice.backgroundColor = arrTabColor[1]
btnSettings.backgroundColor = arrTabColor[2]
btnMyOrder.backgroundColor = arrTabColor[3]
btnLogout.backgroundColor = arrTabColor[4]
let selectedColor = UIColor(red: 40/255, green: 142/255, blue: 206.0/255, alpha: 1.0)
if selectedIndex == 0
{
btnHome.backgroundColor = selectedColor
}
else if selectedIndex == 1
{
btnInvoice.backgroundColor = selectedColor
}
else if selectedIndex == 2
{
btnSettings.backgroundColor = selectedColor
}
else if selectedIndex == 3
{
btnMyOrder.backgroundColor = selectedColor
}
else if selectedIndex == 4
{
btnLogout.backgroundColor = selectedColor
}
}
// MARK: - Action Method
#IBAction func HomeClicked(_ sender : AnyObject?)
{
setTabbarImage(0)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[0])
}
#IBAction func InvoiceClicked(_ sender : AnyObject?)
{
setTabbarImage(1)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[1])
}
#IBAction func SettingClicked(_ sender : AnyObject?)
{
setTabbarImage(2)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[2])
}
#IBAction func MyorderClicked(_ sender : AnyObject?)
{
setTabbarImage(3)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[3])
}
#IBAction func logoutClicked(_ sender : AnyObject?)
{
setTabbarImage(4)
let alert = UIAlertController(title: "", message: "Are you sure want to logout?", preferredStyle: UIAlertControllerStyle.alert)
let CancelAction = UIAlertAction(title: "NO", style: .default) { (action:UIAlertAction!) in
}
alert.addAction(CancelAction)
let OKAction = UIAlertAction(title: "YES", style: .default) { (action:UIAlertAction!) in
// var isNav : Bool! = false
//for objChild in (self.parent?.childViewControllers)!
// {
// if objChild.isKind(of: LoginVC.self)
// {
// self.navigationController!.popToViewController(objChild, animated: true)
// CommonMethods.removeCustomObject(Constants.kUserProfile)
//
// isNav = true
// break
//
// }
// }
// if !isNav
// {
// CommonMethods.removeCustomObject(Constants.kUserProfile)
// let aNavController = (AppDelegate.getDelegate().window!.rootViewController! as! UINavigationController)
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
// var aVCObj = UIViewController()
// aVCObj = storyboard.instantiateViewController(withIdentifier: "LoginVC")
// var aMutArr = aNavController.viewControllers
// aMutArr.insert(aVCObj, at: 0)
// aNavController.viewControllers = aMutArr
// aNavController.popToRootViewController(animated: true)
// }
}
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
// MARK: - Action Method
}

Related

Follow and unfollowing button issue while closing & reopening the app

In the Tab Bar Controller here are four tabs namely home, discover, notification and user profile. The discover tab controller lists all the users in Firebase. The users are listed with username and follow button. If the current user taps on follow, the title is set to following.
protocol PeopleTableViewCellDelegate {
func goToProfileUserVC(userId: String)
}
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var followButton: UIButton!
var delegate: PeopleTableViewCellDelegate?
var user: User? {
didSet {
updateView()
}
}
func updateView() {
nameLabel.text = user?.username
if let photoUrlString = user?.profileImageUrl {
let photoUrl = URL(string: photoUrlString)
profileImage.sd_setImage(with: photoUrl, placeholderImage: UIImage(named: "placeholderImg"))
}
if user!.isFollowing! {
configureUnFollowButton()
} else {
configureFollowButton()
}
}
func configureFollowButton() {
followButton.layer.borderWidth = 1
followButton.layer.borderColor = UIColor(red: 226/255, green: 228/255, blue: 232.255, alpha: 1).cgColor
followButton.layer.cornerRadius = 5
followButton.clipsToBounds = true
followButton.setTitleColor(UIColor.white, for: UIControlState.normal)
followButton.backgroundColor = UIColor(red: 69/255, green: 142/255, blue: 255/255, alpha: 1)
followButton.setTitle("Follow", for: UIControlState.normal)
followButton.addTarget(self, action: #selector(self.followAction), for: UIControlEvents.touchUpInside)
}
func configureUnFollowButton() {
followButton.layer.borderWidth = 1
followButton.layer.borderColor = UIColor(red: 226/255, green: 228/255, blue: 232.255, alpha: 1).cgColor
followButton.layer.cornerRadius = 5
followButton.clipsToBounds = true
followButton.setTitleColor(UIColor.black, for: UIControlState.normal)
followButton.backgroundColor = UIColor.clear
followButton.setTitle("Following", for: UIControlState.normal)
followButton.addTarget(self, action: #selector(self.unFollowAction), for: UIControlEvents.touchUpInside)
}
func followAction() {
if user!.isFollowing! == false {
Api.Follow.followAction(withUser: user!.id!)
configureUnFollowButton()
user!.isFollowing! = true
}
}
func unFollowAction() {
if user!.isFollowing! == true {
Api.Follow.unFollowAction(withUser: user!.id!)
configureFollowButton()
user!.isFollowing! = false
}
}
override func awakeFromNib() {
super.awakeFromNib()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.nameLabel_TouchUpInside))
nameLabel.addGestureRecognizer(tapGesture)
nameLabel.isUserInteractionEnabled = true
}
func nameLabel_TouchUpInside() {
if let id = user?.id {
delegate?.goToProfileUserVC(userId: id)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Here code for duplicate user:
func loadUsers() {
// self.users = []
API.User.observeUser { (user) in
self.isFollowing(userId: user.id!, completed: { (value) in
user.isFollowing = value
self.users.append(user)
self.tableView.reloadData()
})
}
}
My issue: The list show at Discover tab is duplicated and when user taps on the follow button, it's title is set to following. But if the user closes and reopens the app, upon return to Discover tab the previously followed user's button remains follow despite the data having been inserted correctly in Firebase.
Any help much appreciated please...
I am writting this as an answer as there is (probably) not enough space to write it as a comment.
First of all your set up looks a bit messy, it seems that some details are handled locally and some on Firebase, and nothing in your code is triggering loadUsers().
I would advice you to set up as following:
Create a class named followingUsers give them the necessary properties e.g following and set your initializer. Then add var followingUsersArray = [followingUsers]() inside your ViewController.
Put the obeserve Firebase function in your viewDidLoad(), get
all the data and put it in your followingUsersArray then reload your tableView.
Create a UITableViewCell class and give it the desired properties, then set a method to configure the cell. Call that method from cellAtRow and pass it the values from the followingUsersArray.

Table View Cells are not reaching to same array

I am trying to build an app which has object of Items and a controller for it which is called ItemsController. Also on my screen I suppose to have a table view and a button on it. The functionality of button is when it is clicked it needs to check favoriteItems array in ItemsController if it is found in that array remove element, if it isn't found there then append it to array. Operations for remove and append good but unfortunately all cells are not working together. They creates their own favoriteItems array.
To achieve this I tried to make ItemsController to be a singleton. I changed class to a struct and called ItemsController.sharedInstance everywhere. It actually solved a lot of my problem and I believe that the source I learnt this is not wrong about it. But why my tableview cells doesn't use ItemsController's favoriteItems array instead create theirs?
struct ItemsController {
var favoriteItems = [Items]()
static var sharedInstance = ItemsController()
init(){
itemsArray = [...items...]
}
}
class TableViewCell: UITableViewCell {
#IBOutlet weak var favoriteButton: UIButton!
let buttonFirstColor : UIColor = UIColor.clear
let buttonSecondColor : UIColor = UIColor(red: 224/255.0, green: 74/255.0, blue: 94/255.0, alpha: 1.0)
var itemsController = ItemsController.sharedInstance
var itemDedicated = Items(name: "", pic: "", aciklama: "")
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
favoriteButton.layer.cornerRadius = 0.5 * favoriteButton.bounds.size.width
favoriteButton.backgroundColor = UIColor.clear
favoriteButton.layer.borderColor = UIColor(red: 224/255.0, green: 74/255.0, blue: 94/255.0, alpha: 1.0).cgColor
favoriteButton.layer.borderWidth = 4.0
favoriteButton.clipsToBounds = true
setFavoriteButton()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func favoriteButtonClicked(_ sender: Any) {
var favoriteFound = false
for items in itemsController.favoriteItems{
if(items.name == itemDedicated.name){
favoriteFound = true }
}
if(favoriteFound){
itemsController.favoriteItems.remove(at: itemsController.favoriteItems.index(of: itemDedicated)!)
} else {
itemsController.favoriteItems.append(itemDedicated)
}
setFavoriteButton()
}
private func setFavoriteButton(){
var favoriteFound = false
for items in itemsController.favoriteItems{
if(items.name == itemDedicated.name){
favoriteFound = true }
}
if(favoriteFound){
favoriteButton.backgroundColor = buttonSecondColor
favoriteButton.setTitleColor(buttonFirstColor, for: .normal)
} else {
favoriteButton.backgroundColor = buttonFirstColor
favoriteButton.setTitleColor(buttonFirstColor, for: .normal)
}
}
}

Swift 3 - Changing background colour of all view controllers, via switch(Dark mode/Night mode)

i crated a switch that lets the user change the background colour (dark mode). This only works on the view controller that the code is linked with. How would i set it so when the switch is activated to either dark or light mode, every view controller in my application would change, not just the one. Heres my code:
import UIKit
class DarkMode: UIViewController {
#IBOutlet var DarkSwitch: UISwitch!
#IBOutlet var LightSwitch: UISwitch!
var DarkisOn = Bool()
var LightisOn = Bool()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let DarkDefault = UserDefaults.standard
DarkisOn = DarkDefault.bool(forKey: "DarkDefault")
let LightDefault = UserDefaults.standard
LightisOn = LightDefault.bool(forKey: "LightDefault")
if (DarkisOn == true) {
DarkSwitch.isOn = true
LightSwitch.isOn = false
//run dark theme
DarkTheme()
}
if (LightisOn == true) {
DarkSwitch.isOn = false
LightSwitch.isOn = true
//run light theme
LightTheme()
}
}
func DarkTheme() //dark colour
{
self.view.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0)
}
func LightTheme() //light colour
{
self.view.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
#IBAction func DarkAction(_ sender: Any)
{
DarkSwitch.isOn = true
LightSwitch.isOn = false
//run dark theme func
DarkTheme()
let DarkDefault = UserDefaults.standard
DarkDefault.set(true, forKey: "DarkDefault")
let LightDefault = UserDefaults.standard
LightDefault.set(false, forKey: "LightDefault")
}
#IBAction func LightAction(_ sender: Any)
{
DarkSwitch.isOn = false
LightSwitch.isOn = true
//run light theme func
LightTheme()
let DarkDefault = UserDefaults.standard
DarkDefault.set(false, forKey: "DarkDefault")
let LightDefault = UserDefaults.standard
LightDefault.set(true, forKey: "LightDefault")
}
}
You can create a base class like this (This is something I have used.)
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.barTintColor = MainColor
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]//user global variable
self.navigationController?.navigationBar.barStyle = UIBarStyle.black //user global variable
self.navigationController?.navigationBar.tintColor = UIColor.white //user global variable
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Setup all your theme here.
All the color value should be global which you can change from another ViewController.
And now declare your all ViewControllers like this
class HomeViewController: BaseViewController {
}
This way HomeViewController will have all the appearance you set in BaseViewController.
Now All you have to do is change those global variables for color value.
For one of my projects I created a class that controlled the UI colour scheme across all my ViewControllers.
class UIColourScheme {
func set(for viewController: UIViewController) {
viewController.view.backgroundColor = bgColour
...
}
var bgColour = UIColor.black
static let instance = UIColourScheme()
}
I would then call this function in viewDidLoad() for every ViewController
class MyViewController : UIViewController {
func viewDidLoad() {
...
UIColourScheme.instance.set(for:self)
}
}
My colour scheme class setup colours for everything but it could be simplified to just the background colour as above.
you can use this
protocol colorable {
func setcolor(color: UIColor)
}
class HomeVC: colorable {
}
I modified viewWillAppear method. And added dark mode based on the time of the day.
You do not need to format the time/hours you receive back you may wanna use it as is in conditional statement.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
// get time of the day
let hour = Calendar.current.component(.hour, from: Date())
print(hour)
if hour >= 14 {
overrideUserInterfaceStyle = .dark
}
else {
overrideUserInterfaceStyle = .light
}
}

How can I set two UITextFields together with Swift?

I am trying to put two UITextFields with Swift together similar to this question: UITextField Set Border.
So the result should be one UITextField above the other and they will collapse on the border-bottom of the first one.
I am following the code that is on the question related:
tfUser.layer.borderWidth = 1
tfUser.layer.borderColor = UIColor(red: 69/255, green: 106/255, blue: 153/255, alpha: 1).CGColor
tfUser.layer.cornerRadius = 5
tfUser.clipsToBounds = true; //I am not able to equal this property to 'YES' so I put 'true'. Looking on the documentation I could see that it only accepts a boolean value.
tfPassword.layer.borderWidth = 2
tfPassword.layer.borderColor = UIColor(red: 69/255, green: 106/255, blue: 153/255, alpha: 1).CGColor
tfPassword.layer.cornerRadius = 5
tfPassword.clipsToBounds = true; //I am not able to equal this property to 'YES' so I put 'true'. Looking on the documentation I could see that it only accepts a boolean value.
I also have tried with the accepted answer but it does not recognize that property (I tried with borderStyle but it also does not work as I cannot set it to UITextBorderStyleNone).
The result I am getting right now is:
Am I missing something? What can I do to put them together?
Thanks in advance!
for your concept
step-1
Create One UIView and add the two textfield subview of UIVIew.
Step-2
set your yourTextField.borderStyle as None and set border width and border color
step-3
set the corner radius of UIView as UIView.layer.cornerRadius = 5
updated answer
you can downloaded the sample project in here
create one UIVIew, and two textfields and set your yourTextField.borderStyle = .None
#IBOutlet weak var backview: UIView!
#IBOutlet weak var txtUserName: UITextField!
#IBOutlet weak var txtpassword: UITextField!
and called in your page like
override func viewDidLoad() {
super.viewDidLoad()
self.changecornerRadius(self.txtpassword)
self.changecornerRadius(self.txtUserName)
self.changecornerRadiussd(self.backview)
}
func changecornerRadius(textfield: UITextField) {
textfield.layer.borderWidth = 1
textfield.layer.borderColor = UIColor.lightGrayColor().CGColor
textfield.layer.cornerRadius = 2
textfield.clipsToBounds = true
let paddingView = UIView(frame:CGRectMake(0, 0, 30, 30))
textfield.leftView=paddingView;
textfield.leftViewMode = .Always
}
func changecornerRadiussd(currentView: UIView) {
currentView.layer.borderWidth = 1
currentView.layer.borderColor = UIColor.blueColor().CGColor
currentView.layer.cornerRadius = 5
currentView.clipsToBounds = true
}
you get the output as
To set UITextBorderStyleNone in Swift:
yourTextField.borderStyle = .None
I think you have 3 solutions and both use UITextBorderStyleNon‌e:
add 2 background image
make grouped UITableView, cells should contain UITextFields
Draw it in frameRect method
I recommend to use number two
the best way to achieve this ..have a look below code
#IBAction func showLoginPasswordAlert(sender: UIButton) {
var alert = UIAlertController(title: "User login", message: "login password ..!!", preferredStyle:
UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(configurationTextFieldLogin)
alert.addTextFieldWithConfigurationHandler(configurationTextFieldPassword)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("User click Ok button")
// print(self.textField.text)
}))
self.presentViewController(alert, animated: true, completion: {
print("completion block")
})
}
// func to add login textfield
func configurationTextFieldLogin(textField: UITextField!)
{
if let aTextField = textField {
textField.text = "Login"
}
}
// function to add password textfield
func configurationTextFieldPassword(textField: UITextField!)
{
if let aTextField = textField {
textField.text = "Password"
}
}
or you can edit in your best way..

How do I get the index out of the optional func didMoveToPage?

I am using uacaps/CAPSPageMenu in my app and I cannot figure out how to get the number of the active page so I can show a webpage corresponding to the page. In the code CAPSPageMenu.swift the following code is used.
import UIKit
#objc public protocol CAPSPageMenuDelegate {
// MARK: - Delegate functions
optional func willMoveToPage(controller: UIViewController, index: Int)
optional func didMoveToPage(controller: UIViewController, index: Int)
}
I think the index: Int part in the optional func didMoveToPage is giving me a number of the current page. Is this right? How do I get that index number in the ViewController.swift code?
EDIT
In CAPSPageMenu I found this code.
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView.isEqual(controllerScrollView) {
// Call didMoveToPage delegate function
let currentController = controllerArray[currentPageIndex]
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
The ViewController.swift code as shown below.
//
// ViewController.swift
// PageMenuDemoStoryboard
//
// Created by Niklas Fahl on 12/19/14.
// Copyright (c) 2014 CAPS. All rights reserved.
//
import UIKit
var websiteArray = ["http://website_0", "http://website_1", "http://website_2"]
//class ViewController: UIViewController {
class ViewController: UIViewController,CAPSPageMenuDelegate {
var pageMenu : CAPSPageMenu?
var pageNumber = 0
#IBOutlet weak var showWebsite: UIWebView!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// MARK: - UI Setup
self.title = "App Title"
self.navigationController?.navigationBar.barTintColor = UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.barStyle = UIBarStyle.Black
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orangeColor()]
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "<-", style: UIBarButtonItemStyle.Done, target: self, action: "didTapGoToLeft")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "->", style: UIBarButtonItemStyle.Done, target: self, action: "didTapGoToRight")
// MARK: - Scroll menu setup
// Initialize view controllers to display and place in array
var controllerArray : [UIViewController] = []
let controller1 : TestCollectionViewController = TestCollectionViewController(nibName: "TestCollectionViewController", bundle: nil)
controller1.title = "Item_0"
controller1.photoNameArray = ["Item_0.png"]
controllerArray.append(controller1)
let controller2 : TestCollectionViewController = TestCollectionViewController(nibName: "TestCollectionViewController", bundle: nil)
controller2.title = "Item_1"
controller2.photoNameArray = ["Item_1.png"]
controllerArray.append(controller2)
let controller3 : TestCollectionViewController = TestCollectionViewController(nibName: "TestCollectionViewController", bundle: nil)
controller3.title = "Item_2"
controller3.photoNameArray = ["Item_2.png"]
controllerArray.append(controller3)
// Customize menu (Optional)
let parameters: [CAPSPageMenuOption] = [
.ScrollMenuBackgroundColor(UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0)),
.ViewBackgroundColor(UIColor(red: 20.0/255.0, green: 20.0/255.0, blue: 20.0/255.0, alpha: 1.0)),
.SelectionIndicatorColor(UIColor.orangeColor()),
.BottomMenuHairlineColor(UIColor(red: 70.0/255.0, green: 70.0/255.0, blue: 80.0/255.0, alpha: 1.0)),
.MenuItemFont(UIFont(name: "HelveticaNeue", size: 13.0)!),
.MenuHeight(30.0),
.MenuItemWidth(90.0),
.CenterMenuItems(true)
]
// Initialize scroll menu
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, self.view.frame.height * 0.71, self.view.frame.width, self.view.frame.height * 0.33), pageMenuOptions: parameters)
self.addChildViewController(pageMenu!)
self.view.addSubview(pageMenu!.view)
pageMenu!.didMoveToParentViewController(self)
pageMenu!.delegate = self
func willMoveToPage(controller: UIViewController, index: Int) {
let subview=controller as! ViewController
subview.pageNumber=index;
}
}
func didTapGoToLeft() {
var currentIndex = pageMenu!.currentPageIndex
if currentIndex > 0 {
pageMenu!.moveToPage(currentIndex - 1)
}
setWebPage()
}
func didTapGoToRight() {
var currentIndex = pageMenu!.currentPageIndex
if currentIndex < pageMenu!.controllerArray.count {
pageMenu!.moveToPage(currentIndex + 1)
}
setWebPage()
}
func setWebPage() {
var currentIndex = pageMenu!.currentPageIndex
switch currentIndex {
case 0:
let url = NSURL (string: "\(websiteArray[0])");
let requestObj = NSURLRequest(URL: url!);
showWebsite.loadRequest(requestObj);
break
case 1:
let url = NSURL (string: "\(websiteArray[1])");
let requestObj = NSURLRequest(URL: url!);
showWebsite.loadRequest(requestObj);
break
case 2:
let url = NSURL (string: "\(websiteArray[2])");
let requestObj = NSURLRequest(URL: url!);
showWebsite.loadRequest(requestObj);
break
default:
break
}
}
// MARK: - Container View Controller
override func shouldAutomaticallyForwardAppearanceMethods() -> Bool {
return true
}
override func shouldAutomaticallyForwardRotationMethods() -> Bool {
return true
}
}
When I tap the buttons it is working like it should. The navigation bar shows the active page and the picture (collectionViewController) that belongs to the active page is shown and also the webpage that belongs to the active page is shown. But I do not want to use the buttons. I want to use the collectionViewController so that when I swipe the image to the next page the new image is shown (this is working already) and the corresponding webpage also (this is not working because of not setting the pageMenu!.currentPageIndex).
How to activate the didTapGoToLeft and Right methods when I swipe the picture?
The CAPSPageMenu provides a delegate method that inform's its delegate that the page has changed. These are the delegate methods you listed in your question.
So, in your ViewController class you need to implement these delegate methods.
First, tell the compiler that your class implements the protocol:
class ViewController:UIViewController,CAPSPageMenuDelegate
Now, you need to set the view controller as the delegate. Where you create the CAPSPageMenu you will need something like this -
pageMenu.delegate=self
Finally, implement the delegate methods. The CAPSPageMenu is provided with an array of view controllers that it manages. You haven't given the precise details of these, but I am assuming that they implement some class which I am calling SubViewController. Define an integer property pageNumber in this class and then your delegate method can simply be -
func willMoveToPage(controller: UIViewController, index: Int) {
let subview=controller as! SubViewController
subview.pageNumber=index;
}
Then, in your SubViewController you can implement a setter on pageNumber that does whatever it needs to when the page number changes. In your delegate method you could also use the index to index into an array of strings (URLs say) and then set a string/URL property on the sub view controller - it depends on what you are trying to do.

Resources