How can I scroll through an array under the current situation? - ios

I have an array of strings, and I want to set them up, so the user can scroll through the strings, and which ever one it lands on that one is selected, but I am unsure on how to do it. I was thinking of using a scroll view or a pagevc, but those take up the whole view, and it will show one string per page. Instead I need them side by side so I can see the value one ahead or one behind. A roadmap on how to execute this would be perfect, I am so lost on this component.
func numberOfItemsInCarousel(carousel: iCarousel) -> Int {
//getInfo()
return animal.count
}
func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView {
var labelsubject: UILabel
var itemView: UIImageView
var labelname: UILabel
var cardimage: UIImageView
var cardtypeimage: UIImageView
if(view == nil){
itemView = UIImageView(frame:CGRect(x:0, y:0, width:400, height:100))
itemView.image = UIImage(named: "page")
itemView.contentMode = .Center
labelsubject = UILabel(frame: itemView.bounds)
labelsubject.backgroundColor = UIColor.clearColor()
labelsubject.textAlignment = .Center
labelsubject.textColor = UIColor.whiteColor()
labelsubject.tag = 1
itemView.addSubview(labelsubject)
}else{
itemView = view as! UIImageView;
labelsubject = itemView.viewWithTag(1) as! UILabel!
}
selectedData.anim = animal[index]
return itemView
}
func carouselDidEndDragging(carousel: iCarousel, willDecelerate decelerate: Bool) {
if !decelerate {
print(carousel.currentItemIndex)
//text[carousel.currentItemIndex]
}
}
func carouselDidEndDecelerating(carousel: iCarousel) {
print(carousel.currentItemIndex)
//text[carousel.currentItemIndex]
}

Related

Swift - How to add tap gesture to array of UIViews?

Looking to add a tap gesture to an array of UIViews - without success. Tap seems not to be recognised at this stage.
In the code (extract) below:
Have a series of PlayingCardViews (each a UIView) showing on the main view.
Brought together as an array: cardView.
Need to be able to tap each PlayingCardView independently (and then to be able to identify which one was tapped).
#IBOutlet private var cardView: [PlayingCardView]!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapCard(sender: )))
for index in cardView.indices {
cardView[index].isUserInteractionEnabled = true
cardView[index].addGestureRecognizer(tap)
cardView[index].tag = index
}
}
#objc func tapCard (sender: UITapGestureRecognizer) {
if sender.state == .ended {
let cardNumber = sender.view.tag
print("View tapped !")
}
}
You need
#objc func tapCard (sender: UITapGestureRecognizer) {
let clickedView = cardView[sender.view!.tag]
print("View tapped !" , clickedView )
}
No need to check state here as the method with this gesture type is called only once , also every view should have a separate tap so create it inside the for - loop
for index in cardView.indices {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapCard(sender: )))
I will not recommend the selected answer. Because creating an array of tapGesture doesn't make sense to me in the loop. Better to add gesture within PlaycardView.
Instead, such layout should be designed using UICollectionView. If in case you need to custom layout and you wanted to use scrollView or even UIView, then the better approach is to create single Gesture Recognizer and add to the superview.
Using tap gesture, you can get the location of tap and then you can get the selectedView using that location.
Please refer to below example:
import UIKit
class PlayCardView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.red
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.red
}
}
class SingleTapGestureForMultiView: UIViewController {
var viewArray: [UIView]!
var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView(frame: UIScreen.main.bounds)
view.addSubview(scrollView)
let tapGesture = UITapGestureRecognizer(target: self,
action: #selector(tapGetsure(_:)))
scrollView.addGestureRecognizer(tapGesture)
addSubviews()
}
func addSubviews() {
var subView: PlayCardView
let width = UIScreen.main.bounds.width;
let height = UIScreen.main.bounds.height;
let spacing: CGFloat = 8.0
let noOfViewsInARow = 3
let viewWidth = (width - (CGFloat(noOfViewsInARow+1) * spacing))/CGFloat(noOfViewsInARow)
let viewHeight = (height - (CGFloat(noOfViewsInARow+1) * spacing))/CGFloat(noOfViewsInARow)
var yCordinate = spacing
var xCordinate = spacing
for index in 0..<20 {
subView = PlayCardView(frame: CGRect(x: xCordinate, y: yCordinate, width: viewWidth, height: viewHeight))
subView.tag = index
xCordinate += viewWidth + spacing
if xCordinate > width {
xCordinate = spacing
yCordinate += viewHeight + spacing
}
scrollView.addSubview(subView)
}
scrollView.contentSize = CGSize(width: width, height: yCordinate)
}
#objc
func tapGetsure(_ gesture: UITapGestureRecognizer) {
let location = gesture.location(in: scrollView)
print("location = \(location)")
var locationInView = CGPoint.zero
let subViews = scrollView.subviews
for subView in subViews {
//check if it subclass of PlayCardView
locationInView = subView.convert(location, from: scrollView)
if subView.isKind(of: PlayCardView.self) {
if subView.point(inside: locationInView, with: nil) {
// this view contains that point
print("Subview at \(subView.tag) tapped");
break;
}
}
}
}
}
You can try to pass the view controller as parameter to the views so they can call a function on parent view controller from the view. To reduce memory you can use protocols. e.x
protocol testViewControllerDelegate: class {
func viewTapped(view: UIView)
}
class testClass: testViewControllerDelegate {
#IBOutlet private var cardView: [PlayingCardView]!
override func viewDidLoad() {
super.viewDidLoad()
for cardView in self.cardView {
cardView.fatherVC = self
}
}
func viewTapped(view: UIView) {
// the view that tapped is passed ass parameter
}
}
class PlayingCardView: UIView {
weak var fatherVC: testViewControllerDelegate?
override func awakeFromNib() {
super.awakeFromNib()
let gr = UITapGestureRecognizer(target: self, action: #selector(self.viewDidTap))
self.addGestureRecognizer(gr)
}
#objc func viewDidTap() {
fatherVC?.viewTapped(view: self)
}
}

How Do I Properly Use iCarouselOptions with iOS iCarousel?

I'm creating an iOS app with Swift and am using iCarousel from GitHub (installed via cocoapods) and I'm not sure what I'm doing wrong, but I can't seem to get iCarouselOptions I set to have any effect...
What I want to do is simply change the spacing of the UIViews in my carousel (They are too close together and overlapping, which I don't want).
Here is my code:
import UIKit
import iCarousel
class MiniGamesViewController: UIViewController, iCarouselDelegate, iCarouselDataSource {
//Objects
#IBOutlet weak var leaveMinigamesButton: UIButton!
//Variables
var carouselHeight : CGFloat!
var selectionBallSize : CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
leaveMinigamesButton.layer.zPosition = 3
carouselHeight = self.view.frame.size.height - 200
selectionBallSize = self.view.frame.size.width * 0.65
let carousel = iCarousel(frame: CGRect(
x: 0,
y: 100,
width: self.view.frame.size.width,
height: carouselHeight))
carousel.perspective = -0.005
carousel.centerItemWhenSelected = true
carousel.decelerationRate = 0.9
carousel.viewpointOffset = CGSize(width: 0, height: 0) //-selectionBallSize * 1.2
carousel.dataSource = self
carousel.type = .rotary
view.addSubview(carousel)
}
override func viewDidAppear(_ animated: Bool) {
setNeedsStatusBarAppearanceUpdate()
}
//This is how many items there will be in my rotary iCarousel
func numberOfItems(in carousel: iCarousel) -> Int {
return 6
}
//This defines each item or 'cell' in the iCarousel
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let imageView: UIImageView
if view != nil {
imageView = view as! UIImageView
} else {
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: selectionBallSize, height: selectionBallSize))
}
imageView.image = UIImage(named: "orbCyan")
return imageView
}
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
switch (option) {
case .spacing: return value * 2
case .radius: return 200
case .fadeMinAlpha: return 0.5
default: return value
}
}
}
Specifically the very bottom of my code is where the customization
is supposed to take effect, but it doesn't seem to be making any changes when I run the app. At the moment, I'm only concerned with trying to space the UIViews in the carousel to be further apart.
Am I putting the iCarouselOptions function in the right place? Is it even being 'called' at all?
Thanks for your help!
Wouldn't you know it, as soon as I posted this question I found the issue haha (after a day of trying everything). Turns out I was missing the simple line:
carousel.delegate = self
underneath:
carousel.dataSource = self
That totally did the trick and it works now lol. I need a fresh set of eyes :P

When I Scroll the tableView, how can I know which cell is touch the Green Area

The Screen In My Prototype
My question is based onThe image in the link . Because my reputation is not enough, I can't post any image here
We assume that Green Area in the image is fixed.
And, my requirement is that When a cell contains the GA, that cell'saudioPlayer will speak the word in the cell, like AirPod
OR, you can regard my requirement as When a cell contains the GA, the text of that cell's label changes to "Touch the Green"
My question is that when I Scroll the tableView, how can I get which one(Cell) is containing the GA?
But I can’t find a way to get that(some position/index information about That Cell)
could anyone help me ? ObjectiveC solution is OK, Swift solution is better for me, Thank you so much
In this code, I am using GreenArea as in Center of UIView. Some modification from Ruslan's Answer.
#IBOutlet weak var greenAreaVw: UIView!
var contHeight : CGFloat = 0.0
var eachRowHeight : CGFloat = 45
var topSpaceTableView : CGFloat = 62
var GreenAreaOriginY : CGFloat = 0.0
// Give UITableView Edge Insets in ViewDidLoad
contHeight = ((self.view.frame.size.height / 2) - eachRowHeight / 2 - topSpaceTableView)
userTblVw.contentInset = UIEdgeInsets(top: contHeight, left: 0, bottom: contHeight, right: 0)
userTblVw.contentOffset.y = -contHeight
GreenAreaOriginY = greenAreaVw.frame.origin.y
/*------------------- -----------------------*/
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
checkCells()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
checkCells()
}
func checkCells() {
userTblVw.visibleCells.forEach { cell in
if let indexPath = userTblVw.indexPathForCell(cell) {
let rect = userTblVw.rectForRowAtIndexPath(indexPath)
let convertedRect = self.userTblVw.convertRect(rect, toView: self.view)
if convertedRect.origin.y >= GreenAreaOriginY && convertedRect.origin.y < (GreenAreaOriginY + eachRowHeight)
{
let contFloat : CGFloat = (eachRowHeight * CGFloat(indexPath.row)) - contHeight
userTblVw.setContentOffset(CGPoint(x: 0, y: contFloat), animated: true)
}
}
}
}
Find below Screenshots:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// We check cells here to set the state of whether it contains the green or not before the scrolling
checkCells()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// And we are continuously checking cells while scrolling
checkCells()
}
func checkCells() {
tableView.visibleCells.forEach { cell in
if let indexPath = tableView.indexPath(for: cell) {
let rect = tableView.rectForRow(at: indexPath)
// This is the rect in your VC's coordinate system (and not the table view's one)
let convertedRect = self.view.convert(rect, from: tableView)
if convertedRect.contains(greenArea.frame) {
cell.textLabel?.text = "Touch the Green"
} else {
cell.textLabel?.text = "Does not touch the Green"
}
}
}
}
How about something like:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
[0, 1, 2].forEach {
let rect = tableView.rectForRow(at: IndexPath(row: $0, section: 0))
if rect.contain(GAView.frame) {
// play sound here
}
}
}

[UITextField retain]: message sent to deallocated instance

I get this message:
[UITextField retain]: message sent to deallocated instance.
I understand the message BUT I do not know what "message" is sent and how to stop it from happening....
This code produces the error:
func dismissController() {
self.view.endEditing(true)
self.dismissViewControllerAnimated(false, completion: nil)
}
While the following works "fine" I am not sure why I have to delay before dismissing the controller:
func dismissController() {
self.view.endEditing(true)
let delay = 0.75 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
}
}
EDIT:(almost full code):
#IBOutlet weak var locationTextView: UITextField!
#IBOutlet weak var userIDTextView: UITextField!
var treeLocationArray = NSMutableArray()
var treeUserIDArray = NSMutableArray()
let pickerView = UIPickerView()
var pickerButton = UIButton()
var keyboardButton = UIButton()
var locationIsSelected = true
override func viewDidLoad() {
super.viewDidLoad()
//....
locationTextView.delegate = self
userIDTextView.delegate = self
//Get the Plist... etc
treeLocationArray = dict?.objectForKey("Location") as! NSMutableArray
treeUserIDArray = dict?.objectForKey("UserID") as! NSMutableArray
locationTextView.text = userPrefs.objectForKey("DefaultLocation") as? String
userIDTextView.text = userPrefs.objectForKey("DefaultName") as? String
locationTextView.text = userPrefs.objectForKey("DefaultLocation") as? String
/// Create a view for the Accessory View
let customView = UIView(frame: CGRectMake(0, 0, 10, 50))
customView.backgroundColor = UIColor.lightGrayColor()
/// Setup the picker button
pickerButton = UIButton(frame: CGRectMake(60 , 8, 32, 32) )
pickerButton.setImage(UIImage(named:"dropIcon"), forState: .Normal)
pickerButton.tintColor = UIColor.blueColor()
pickerButton.addTarget(self, action: #selector(UserDefaultsViewController.pickerTapped), forControlEvents: UIControlEvents.TouchUpInside)
customView.addSubview(pickerButton)
/// Setup the keyboard button
keyboardButton = UIButton(frame: CGRectMake(10 , 8, 32, 32) )
keyboardButton.setImage(UIImage(named:"keyboardIcon"), forState: .Normal)
keyboardButton.tintColor = UIColor.blueColor()
keyboardButton.addTarget(self, action: #selector(UserDefaultsViewController.keyboardTapped), forControlEvents: UIControlEvents.TouchUpInside)
customView.addSubview(keyboardButton)
locationTextView.inputAccessoryView = customView
userIDTextView.inputAccessoryView = customView
}
func textFieldDidBeginEditing(textField: UITextField) {
if textField == locationTextView {
locationIsSelected = true
}
if textField == userIDTextView {
locationIsSelected = false
}
self.pickerView.reloadAllComponents()
}
func keyboardTapped(){
if locationIsSelected {
locationTextView.resignFirstResponder()
locationTextView.inputView = nil
locationTextView.becomeFirstResponder()
}
else {
userIDTextView.resignFirstResponder()
userIDTextView.inputView = nil
userIDTextView.becomeFirstResponder()
}
}
func pickerTapped(){
if locationIsSelected {
locationTextView.resignFirstResponder()
locationTextView.inputView = nil
locationTextView.inputView = pickerView
locationTextView.becomeFirstResponder()
}
else {
userIDTextView.resignFirstResponder()
userIDTextView.inputView = nil
userIDTextView.inputView = pickerView
userIDTextView.becomeFirstResponder()
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var numberOfComponents = Int()
if locationIsSelected {
numberOfComponents = treeLocationArray.count
}
else {
numberOfComponents = treeUserIDArray.count
}
return numberOfComponents
}
func pickerView(pickerView: UIPickerView, numberOfRowsInSection section: Int) -> Int {
var numberOfComponents = Int()
if locationIsSelected {
numberOfComponents = treeLocationArray.count
}
else {
numberOfComponents = treeUserIDArray.count
}
return numberOfComponents
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var componetString = String()
if locationIsSelected {
componetString = (treeLocationArray[row] as? String)!
}
else {
componetString = (treeUserIDArray[row] as? String)!
}
return componetString
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if locationIsSelected {
if treeLocationArray.count >= 1 {
locationTextView.text = treeLocationArray[row] as? String
}
}
else {
if treeUserIDArray.count >= 1 {
userIDTextView.text = treeUserIDArray[row] as? String
}
}
}
This issue happens because you have call to dismissViewControllerAnimated. Due to VC life cycle all objects, that this VC holds will be deallocated. That means, that all manipulations with UI after dismiss are not memory-safe.
From the documentation:
This method looks at the current view and its subview hierarchy for
the text field that is currently the first responder. If it finds one,
it asks that text field to resign as first responder. If the force
parameter is set to true, the text field is never even asked; it is
forced to resign.
So, your VC had been deallocated while endEditing was looking thorough hierarchy, as I guess. It's the only one reason, that may cause memory problem.
Why do you need call to endEditing before dismissing? simply dismiss VC without this call. if you have logic, that depends on endEditing - separate it and call instead of endEditing. Hope this helps.
UPDATE:
Try to call endEditing in viewWillDisappear - this triggers view to resign first responder right before it will be dismissed.

How Do I Initialize Two Instances of NSObject in the same ViewController - Swift

Please bear with me. I'm new to programming and new to StackOverflow. I hope that my question will grant me a warm response for entering the programming community. An acquaintance, whose opinion I trust, told me to post this email to him on StackOverflow.
What do I have to do to get two instances of NSObject to work in the same ViewController? I've initialized an NSObject subclass called SideBar and RightSideBar. They both draw from NSObject. The cells in the menu are called created by a TableViewController I created programatically. I followed a tutorial that did everything programmatically because I didn't know that Storyboard is better for building things.
Below is the code base.
EDITED: Sorry for being long winded. I don't know how to make this any shorter and as complete
===========
****Note the SideBar subclass is the left menu. The RightSideBar class has the same initializer setup and is the right menu. I want to be able to make them both appear on the same ViewController in the same instance of the same ViewController if possible.****
This is the left TableViewController:
import UIKit
//this protocol of the sidebar delegate manages the selection of the item in the row.
protocol SidebarTableViewControllerDelegate {
func sidebarControlDidSelectRow(indexPath: NSIndexPath)
}
class SidebarTableViewController: UITableViewController {
//setting up the delegate and array of menu items.
var delegate:SidebarTableViewControllerDelegate?
var tableData:Array <String> = []
var imageData:[UIImage] = []
// MARK: - Table view data source
//Setting up the number of sections in the menu
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//Setting up the number of items in the menu
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
//Setting up the menu look for the main screen after login.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
//configure the cell...
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel?.textColor = UIColor.darkTextColor()
let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
cell!.selectedBackgroundView = selectedView
}
cell!.textLabel!.text = tableData[indexPath.row]
cell!.imageView!.image = imageData[indexPath.row]
return cell!
}
//Setting up the height for each cell of the table
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 45.0
}
//Setting up the selection of the item in the cell.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.sidebarControlDidSelectRow(indexPath)
}
override func viewDidLoad() {
}
override func didReceiveMemoryWarning() {
}
}
This is the right table view controller:
//setting up the RightSidebarControllerDelegate
protocol RightSidebarTableViewControllerDelegate {
func rightSidebarControlDidSelectRow(indexPath: NSIndexPath)
}
class RightSidebarTableViewController: UITableViewController {
//setting up the delegate and array of menu items.
var delegate:RightSidebarTableViewControllerDelegate?
var rightTableData:Array <String> = []
var rightImageData:[UIImage] = []
// MARK: - Table view data source
//Setting up the number of sections in the menu
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//Setting up the number of items in the menu
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rightTableData.count
}
//Setting up the menu look for the main screen after login.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
//configure the cell...
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel?.textColor = UIColor.darkTextColor()
let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
cell!.selectedBackgroundView = selectedView
}
cell!.textLabel!.text = rightTableData[indexPath.row]
cell!.imageView!.image = rightImageData[indexPath.row]
return cell!
}
//Setting up the height for each cell of the table
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 45.0
}
//Setting up the selection of the item in the cell.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.rightSidebarControlDidSelectRow(indexPath)
}
override func viewDidLoad() {
}
override func didReceiveMemoryWarning() {
}
}
Here is where my problems may start with SideBar:NSObject. This is the left SideBar to be initialized:
import UIKit
#objc protocol SideBarDelegate {
func sideBarDidSelectButtonAtIndex (index: Int)
optional func sideBarWillClose()
optional func sideBarWillOpen()
optional func sideBarWillDeinitialize()
}
//this class sets up the actual sidebar.
class SideBar: NSObject, SidebarTableViewControllerDelegate {
//width of the bar, tableview setup, and views for the sidebar
let barWidth:CGFloat = 175.0
let sideBarTableViewTopInset:CGFloat = 25.0
let sideBarContainerView:UIView = UIView()
let sideBarTableViewController:SidebarTableViewController = SidebarTableViewController()
var originView:UIView!
//var for dynamic effect and controlling the sidebar
var animator:UIDynamicAnimator!
var delegate:SideBarDelegate?
var isSideBarOpen:Bool = false
//initializer for the "SideBar" class.
override init() {
super.init()
}
//initializer for the tableView of menu items.
init(sourceView: UIView, menuItems: Array<String>, menuImages: [UIImage]){
super.init()
//initializing the views and animation for the menu.
originView = sourceView
sideBarTableViewController.tableData = menuItems
sideBarTableViewController.imageData = menuImages
setupSideBar()
animator = UIDynamicAnimator(referenceView: originView)
}
//function for setting up the sidebar.
func setupSideBar () {
//setting up the frame/outline of the side bar.
sideBarContainerView.frame = CGRectMake(-barWidth, originView.frame.origin.y + 45, barWidth, originView.frame.size.height)
//setting up the color of the sidebar.
sideBarContainerView.backgroundColor = UIColor.clearColor()
//disables subviews from being confined to the sidebar.
sideBarContainerView.clipsToBounds = false
//placing the sidebar in the UIView
originView.addSubview(sideBarContainerView)
//adding blur to the menu.
let blurView:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
blurView.frame = sideBarContainerView.bounds
sideBarContainerView.addSubview(blurView)
//setting up controls for the sidebar
sideBarTableViewController.delegate = self
sideBarTableViewController.tableView.frame = sideBarContainerView.bounds
sideBarTableViewController.tableView.clipsToBounds = false
//disabling the scroll feature. Delete to keep the scroll feature.
sideBarTableViewController.tableView.scrollsToTop = false
//This will remove separators in the UITableCell. Delete to keep separators.
sideBarTableViewController.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//This sets the background color of the sidebar and creates the inset.
sideBarTableViewController.tableView.backgroundColor = UIColor.clearColor()
sideBarTableViewController.tableView.contentInset = UIEdgeInsets(top: sideBarTableViewTopInset, left: 0, bottom: 0, right: 0)
//reloads the sidebar and adds the container view to the sideBarTableViewController.
sideBarTableViewController.tableView.reloadData()
sideBarContainerView.addSubview(sideBarTableViewController.tableView)
}
func showSideBar(shouldOpen: Bool){
animator.removeAllBehaviors()
isSideBarOpen = shouldOpen
//simple if and else statements to define the direction of animation and intensity of animation
let gravityX:CGFloat = (shouldOpen) ? 0.5 : -0.5
let magnitude:CGFloat = (shouldOpen) ? 20 : -20
let boundaryX:CGFloat = (shouldOpen) ? barWidth : -barWidth
//controls the behavior of the animation.
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)
}
}
This is the right SideBar:NSObject that will eventually initialize the right menu.
import UIKit
#objc protocol RightSideBarDelegate {
func rightSideBarDidSelectButtonAtIndex (index: Int)
optional func sideBarWillClose()
optional func sideBarWillOpen()
}
class RightSideBar: NSObject, RightSidebarTableViewControllerDelegate {
//width of the bar, tableview setup, and views for the sidebar
let barWidth:CGFloat = 175.0
let rightSideBarTableViewTopInset:CGFloat = 25.0
let rightSideBarContainerView:UIView = UIView()
let rightSideBarTableViewController:RightSidebarTableViewController = RightSidebarTableViewController()
var rightOriginView:UIView!
//var for dynamic effect and controlling the sidebar
var animator:UIDynamicAnimator!
var delegate:RightSideBarDelegate?
var isSideBarOpen:Bool = false
//initializer for the "SideBar" class.
override init() {
super.init()
}
//initializer for the tableView of menu items.
init(rightSourceView: UIView, rightMenuItems: Array<String>, rightMenuImages: [UIImage]){
super.init()
//initializing the views and animation for the menu.
rightOriginView = rightSourceView
rightSideBarTableViewController.rightTableData = rightMenuItems
rightSideBarTableViewController.rightImageData = rightMenuImages
setupSideBar()
animator = UIDynamicAnimator(referenceView: rightOriginView)
}
//function for setting up the sidebar.
func setupSideBar () {
//setting up the frame/outline of the side bar.
rightSideBarContainerView.frame = CGRectMake(rightOriginView.frame.size.width + barWidth , rightOriginView.frame.origin.y + 45, barWidth, rightOriginView.frame.size.height)
//setting up the color of the sidebar.
rightSideBarContainerView.backgroundColor = UIColor.clearColor()
//disables subviews from being confined to the sidebar.
rightSideBarContainerView.clipsToBounds = false
//placing the sidebar in the UIView
rightOriginView.addSubview(rightSideBarContainerView)
//adding blur to the menu.
let blurView:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
blurView.frame = rightSideBarContainerView.bounds
rightSideBarContainerView.addSubview(blurView)
//setting up controls for the sidebar
rightSideBarTableViewController.delegate = self
rightSideBarTableViewController.tableView.frame = rightSideBarContainerView.bounds
rightSideBarTableViewController.tableView.clipsToBounds = false
//disabling the scroll feature. Delete to keep the scroll feature.
rightSideBarTableViewController.tableView.scrollsToTop = false
//This will remove separators in the UITableCell. Delete to keep separators.
rightSideBarTableViewController.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//This sets the background color of the sidebar and creates the inset.
rightSideBarTableViewController.tableView.backgroundColor = UIColor.clearColor()
rightSideBarTableViewController.tableView.contentInset = UIEdgeInsets(top: rightSideBarTableViewTopInset, left: 0, bottom: 0, right: 0)
//reloads the sidebar and adds the container view to the rightSideBarTableViewController.
rightSideBarTableViewController.tableView.reloadData()
rightSideBarContainerView.addSubview(rightSideBarTableViewController.tableView)
}
func showSideBar(shouldOpen: Bool){
animator.removeAllBehaviors()
isSideBarOpen = shouldOpen
//simple if and else statements to define the direction of animation and intensity of animation
let gravityX:CGFloat = (shouldOpen) ? -0.5 : 0.5
let magnitude:CGFloat = (shouldOpen) ? -20 : 20
let boundaryX:CGFloat = (shouldOpen) ? -barWidth : barWidth
//controls the behavior of the animation.
let gravityBehavior: UIGravityBehavior = UIGravityBehavior(items: [rightSideBarContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior: UICollisionBehavior = UICollisionBehavior(items: [rightSideBarContainerView])
collisionBehavior.addBoundaryWithIdentifier("sideBarBoundary", fromPoint: CGPointMake(boundaryX, 20), toPoint: CGPointMake(boundaryX, rightOriginView.frame.size.height))
animator.addBehavior(collisionBehavior)
let pushBehavior:UIPushBehavior = UIPushBehavior(items: [rightSideBarContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = magnitude
animator.addBehavior(pushBehavior)
let sideBarBehavior:UIDynamicItemBehavior = UIDynamicItemBehavior(items: [rightSideBarContainerView])
sideBarBehavior.elasticity = 0.3
animator.addBehavior(sideBarBehavior)
}
func rightSidebarControlDidSelectRow(indexPath: NSIndexPath) {
delegate?.rightSideBarDidSelectButtonAtIndex(indexPath.row)
}
}
Finally this is my current code for the DoubleMenuViewController. Something happens when I segue to the DoubleMenuViewController to break the menus. The menus won't even load. However, if I'm in a SingleMenuViewController that only calls SideBar:NSObject then the code will work so long as I'm only calling one menu. In this DoubleMenuViewController, I have the initialization section commented out for the RightSideBar class because I'm working on a solution. I know this code for this ViewController is garbled. I'm trying everything I can think of. See my remarks after the code to see what I've tried:
import UIKit
class DoubleMenuViewController: UIViewController, SideBarDelegate, RightSideBarDelegate {
var sideBar:SideBar?
var ondemandSideBar:SideBar {
get {
if sideBar == nil {
//setting up the menu items for the sidebar.
sideBar = SideBar(sourceView: self.view, menuItems: ["Home", "Share", "About", "Help"], menuImages: [homeImage!, shareImage!, aboutImage!, helpImage!])
sideBar!.delegate = self
SideBar.new()
}
return sideBar!
}
}
//initializes the "RightSideBar"
var rightSideBar:RightSideBar?
var ondemandRightSideBar:RightSideBar {
get {
if rightSideBar == nil {
rightSideBar = RightSideBar(rightSourceView: self.view, rightMenuItems: [//Other items], rightMenuImages: [//Other Items])
rightSideBar!.delegate = self
RightSideBar.new()
}
return rightSideBar!
}
}
var homeImage = UIImage(named: "Home")
var shareImage = UIImage(named: "Share")
var aboutImage = UIImage(named: "About")
var helpImage = UIImage(named: "Help")
#IBOutlet weak var currentMenuControl: UIBarButtonItem!
#IBAction func currentMenuDisplay(sender: AnyObject) {
if currentMenuControl.tag == 1 {
ondemandSideBar.showSideBar(true)
currentMenuControl.tag = 0
} else {
ondemandSideBar.showSideBar(false)
currentMenuControl.tag = 1
}
}
#IBOutlet weak var progressionMenuControl: UIBarButtonItem!
#IBAction func progressionMenuDisplay(sender: AnyObject) {
if progressionMenuControl.tag == 1 {
ondemandRightSideBar.showSideBar(true)
progressionMenuControl.tag = 0
} else {
ondemandRightSideBar.showSideBar(false)
progressionMenuControl.tag = 1
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sideBarDidSelectButtonAtIndex(index: Int) {
switch index {
//segues
}
}
func rightSideBarDidSelectButtonAtIndex(index: Int) {
switch index {
//segues
}
}
}
Here's what I've tried:
I've tried altering the positioning of CGFloats since SubViews seem
to come from the left.
I've renamed all the RightSideBar variables and class names
everything to overcome a runtime confusion in instance variables and
class names. This includes renaming the initializers that you saw in
the NSObject SubClass and the target view controller.
I've tried using control flow in the viewDidLoad method with a
button tag. I took away the swipe features to show the menu and
added buttons because I thought system was struggling to deal with
the Swipes.
I've tried deinitializing in the SideBar subclass file of NSObject.
All that got me was an infinite loop that crashed the application
after login.
Then I tried ondemand initialization in the
targetViewController.....DoubleMenuViewController and
SingleMenuViewController. I returned to a working menu with buttons
in the SingleMenuViewController but it still won't show the left and
right menu in the DoubleMenuViewController.
Last I tried deinitializing the SideBar (left SideBar) and the RightSideBar in the DoubleMenuViewController. However, when I add println() functions to all my sections the debugger doesn't run the print function for me to get values of objects or even show typed states like "This". I added the print functions because I wasn't sure if I would know when deinitialization and reinitialization occurred.
It seems that my menu is initialized from the SideBar: NSObject file and the RightSideBar:NSObject file. What I mean is that my menu is being created before I hit the target view controller. This isn't a problem for me so long as I can get the compiler to initialize the SideBar and the RightSideBar in the same View Controller, but it won't do that.
I just need to be able to control both menus with swipes or button taps.
I think I have a problem with my initializers overriding each other.
However, I don't know how to fix that problem. I've read through the Swift manual and read articles on the internet. I've also searched StackOverflow.
You ask:
How do I Initialize two instances of NSObject in the same view controller?
Setting aside why you're dealing with NSObject at all (in Objective-C all classes have to subclass from NSObject ultimately, in Swift that's no longer the case), if you want to instantiate two objects, you simply have to have one property for each.
If these are lazily instantiated, as your code snippet suggests, then you have to identify where that lazily instantiated property is referenced (e.g. you might trigger it from a "swipe from edge" gesture) or what have you. Set a breakpoint in the code that references that lazily instantiated property and make sure you're getting there at all.
--
I had some observations on one of your code snippets. You say that you're instantiating your side bar like so:
var sideBar : SideBar?
var ondemandSideBar : SideBar {
get {
if sideBar == nil {
sideBar = SideBar(sourceView, menuItems, menuImage etc.)
sideBar!.delegate
SideBar.new()
}
}
}
I don't think that's what you're really doing because you're not setting the delegate, you're both instantiating the SideBar as well as calling new (which you shouldn't be doing from Swift), you're not returning a value, etc.
Also, that pattern of having a stored property that is instantiated by some computed property has a certain Objective-C je ne sais quoi. I'm inferring that you want a lazily instantiated property. If that's the case, I'd be inclined to use a single lazy stored property. And I'd then set that property lazily using a closure:
I'd expect something like this pattern
protocol SideBarDelegate : class { // specify class so we can use `weak` reference
func didChooseMenuItem(sender: SideBar, item: Int)
}
class SideBar {
weak var delegate: SideBarDelegate? // make sure this is weak to avoid strong reference cycle
}
class ViewController: UIViewController, SideBarDelegate {
lazy var sideBar: SideBar = {
let _sideBar = SideBar(sourceView, menuItems, menuImage, etc.)
_sideBar.delegate = self
return _sideBar
}()
func didChooseMenuItem(sender: SideBar, item: Int) {
// handle it here
}
// etc.
}
This way, the sideBar won't be instantiated until you reference sideBar somewhere in your code, but when you do, it will be instantiated with the code inside that closure.

Resources