pass Data When Long Press in Table view Cell - swift

there is a Table View to show phone contact . i want to send phone number and email to another View Controller when Long Pressed the Cell . Long Press Work Correctly But I cant Pass Data to another View Controller .
enter image description here
VC 1 :
override func viewDidLoad() {
super.viewDidLoad()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longpress))
tbMain.addGestureRecognizer(longPress)
}
Long Press Method for table view cell :
#objc func longpress(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
let touchPoint = sender.location(in: tbMain)
if tbMain.indexPathForRow(at: touchPoint) != nil {
let cell = tbMain.dequeueReusableCell(withIdentifier: "testCell") as! NewContactCell
print("Long press Pressed:)")
self.actionVC = self.storyboard!.instantiateViewController(withIdentifier: "ActionsViewController") as? ActionsViewController
UIView.transition(with: self.view, duration: 0.25, options: [.transitionCrossDissolve], animations: {
self.view.addSubview( self.actionVC.view)
}, completion: nil)
}
}
}
VC 2 :
internal var strPhoneNUmber : String!
internal var strEmail : String!
override func viewDidLoad() {
super.viewDidLoad()
print("Phone: \(strPhoneNUmber!)")
// Do any additional setup after loading the view.
}

Get phone number and email from cell object
self.actionVC.strPhoneNUmber = cell.strPhoneNUmber // get phone number from cell object
self.actionVC. strEmail = cell.strEmail // get email from cell object
code would be like
#objc func longpress(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
let touchPoint = sender.location(in: tbMain)
if tbMain.indexPathForRow(at: touchPoint) != nil {
let cell = tbMain.dequeueReusableCell(withIdentifier: "testCell") as! NewContactCell
print("Long press Pressed:)")
self.actionVC = self.storyboard!.instantiateViewController(withIdentifier: "ActionsViewController") as? ActionsViewController
**self.actionVC.strPhoneNUmber = cell.strPhoneNUmber // get phone number from cell object
self.actionVC. strEmail = cell.strEmail // get email from cell object**
UIView.transition(with: self.view, duration: 0.25, options: [.transitionCrossDissolve], animations: {
self.view.addSubview( self.actionVC.view)
}, completion: nil)
}
}
}

I don't see when your trying to pass the data.. you have quite a few way to perform that action first you can use delegation to achieve passing the data
protocol YourDelegate : class {
func passData(phoneNumber: String, email: String)
}
weak var delegate: YourDelegate?
#objc func longpress(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
let touchPoint = sender.location(in: tbMain)
if tbMain.indexPathForRow(at: touchPoint) != nil {
let cell = tbMain.dequeueReusableCell(withIdentifier: "testCell") as! NewContactCell
print("Long press Pressed:)")
self.actionVC = self.storyboard!.instantiateViewController(withIdentifier: "ActionsViewController") as? ActionsViewController
self.delegate = self
**delegate?.passData(cell.strPhoneNumber, cell.strEmail)**
UIView.transition(with: self.view, duration: 0.25, options: [.transitionCrossDissolve], animations: {
self.view.addSubview( self.actionVC.view)
}, completion: nil)
}
}
}
class ???: UIViewController, YourDelegate {
var strPhoneNUmber : String!
var strEmail : String!
override func viewDidLoad() {
super.viewDidLoad()
print("Phone: \(strPhoneNUmber!)")
// Do any additional setup after loading the view.
}
func passData(phoneNumber: String, email: String) {
handle...
}
}
its not clear to me if the actionVC is the one you want to pass the data to but if so you have an instance.. just set the properties but ill still recommend sticking with the delegation pattern
actionVC.strPhoneNumber = cell.strPhoneNumber
or use a segue
self.performSegue(withIdentifier: "yourIdentifier", sender: arr[indexPath.row])
use prepare for segue to create an instance to set his properties according to the sender..
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destvc = segue.destination as? YourClass
destvc.phoneNumber = sender.phoneNumber as? String
destvc.email = sender.email as? String
}

Related

Trying to switch which photo pops up depending on button clicked Xcode

I am making an app that will display a random quote from a stoic philosopher. Right now, I am stuck on trying to make the correct picture pop up. (User clicks on a Button with the philosopher's name on it, and then a new view pops up with an image of the philosopher and a random quote by him).
class ViewController: UIViewController {
var allQuotes = [String]()
var pictures = [String]()
#IBOutlet var Epictetus: UIButton!
#IBOutlet var Seneca: UIButton!
#IBOutlet var MarcusAurelius: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Create a constant fm and assign it the value returned by FileManager.default (built in system type)
let fm = FileManager.default
// Declares a new constant called path that sets the resource path of ours apps buddle.
// A bundle is a directory containing our compiled program and all our assets
let path = Bundle.main.resourcePath!
// items array will be a constant collection of the names of all the files found in the directory of our app
let items = try! fm.contentsOfDirectory(atPath: path)
// create a loop to go through all of our items...
for item in items {
if item.hasSuffix("jpg"){
pictures.append(item)
}
}
print(pictures)
title = "Stoicism"
if let stoicQuotesURL = Bundle.main.url(forResource: "quotes", withExtension: "txt"){
if let stoicQuotes = try? String(contentsOf: stoicQuotesURL) {
allQuotes = stoicQuotes.components(separatedBy: "\n\n")
}
}
}
#IBAction func buttonTapped(_ sender: UIButton) {
if sender.tag == 0 {
if let vc = storyboard?.instantiateViewController(identifier: "Picture") as? PictureViewController {
vc.selectedImage = pictures[0]
navigationController?.pushViewController(vc, animated: true)
}
}
else if sender.tag == 1 {
if let vc = storyboard?.instantiateViewController(identifier: "Picture") as? PictureViewController {
vc.selectedImage = pictures[1]
navigationController?.pushViewController(vc, animated: true)
}
}
else if sender.tag == 2 {
if let vc = storyboard?.instantiateViewController(identifier: "Picture") as? PictureViewController {
vc.selectedImage = pictures[2]
navigationController?.pushViewController(vc, animated: true)
}
}
}
}
That's the code for my main viewController.
import UIKit
class PictureViewController: UIViewController {
#IBOutlet var picture: UIImageView!
#IBOutlet var imageView: UIImageView!
var selectedImage: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let imageToLoad = selectedImage {
imageView.image = UIImage(named: imageToLoad)
}
}
override func viewWillAppear(_ animated: Bool) {
// doing it for the parent class
super.viewWillAppear(animated)
// if its a nav Cont then it will hide bars on tap...
}
// now make sure it turns off when you go back to the main screen
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
That's the code for the viewController that has the imageView. Right now, the image that's popping up is always the preset (Marcus Aurelius), even though my code looks correct to me. Obviously it isn't (also, I've already debugged and ensured through print statements that the jpg files add to the pictures array correctly).
Any help would be appreciated.
First of all, this code is really silly:
#IBAction func buttonTapped(_ sender: UIButton) {
if sender.tag == 0 {
if let vc = storyboard?.instantiateViewController(identifier: "Picture") as? PictureViewController {
vc.selectedImage = pictures[0]
navigationController?.pushViewController(vc, animated: true)
}
}
else if sender.tag == 1 {
if let vc = storyboard?.instantiateViewController(identifier: "Picture") as? PictureViewController {
vc.selectedImage = pictures[1]
navigationController?.pushViewController(vc, animated: true)
}
}
else if sender.tag == 2 {
if let vc = storyboard?.instantiateViewController(identifier: "Picture") as? PictureViewController {
vc.selectedImage = pictures[2]
navigationController?.pushViewController(vc, animated: true)
}
}
}
Do you see that everything in those lines is identical except for the numbers? So make the number a variable:
#IBAction func buttonTapped(_ sender: UIButton) {
if let vc = storyboard?.instantiateViewController(identifier: "Picture") as? PictureViewController {
print(sender.tag)
vc.selectedImage = pictures[sender.tag]
navigationController?.pushViewController(vc, animated: true)
}
}
See how much shorter and clearer that is? Okay, I've also added a print statement. This will print the tag to the console. You need to make sure that your buttons do have the right tags. If they do, your code should work.

Delegates and protocols with VC not connected

I have a parent view controller i.e. HomeViewController which has a navigation bar button via which a user can trigger an alert and enter a string. This string needs to be passed to the child view controller.
Here is the relevant code in the parent view controller:
protocol NewSectionDelegate {
func sendSectionName(name : String)
}
class HomeViewController: UIViewController {
var sectionNameDelegate : NewSectionDelegate?
func addCardAsChild() { // add the child VC to the parent VC
if cardViewController == nil {
cardViewController = CardViewController()
addViewController(newViewController: cardViewController!)
} else {
addViewController(newViewController: cardViewController!)
}
}
func triggerAlert() {
let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
alertController.addTextField(configurationHandler:
{(_ textField: UITextField) -> Void in //txtview customization
})
let addAction = UIAlertAction(title: "Add", style: .default) { _ in
guard let sectionName = alertController.textFields?.first?.text else { return }
self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
}
alertController.addAction(addAction)
self.present(alertController, animated: true, completion: nil)
}
And here is the child view controller:
class CardViewController: UIViewController, NewSectionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let homeViewController = HomeViewController()
homeViewController.sectionNameDelegate = self
}
func sendSectionName(name: String) {
print("received name:\(name)") // This line of code is never called
}
The data is not getting passed and I have no idea why.
Is this what you are looking for?
protocol NewSectionDelegate {
func sendSectionName(name : String)
}
class HomeViewController: UIViewController {
var sectionNameDelegate : NewSectionDelegate?
var cardViewController = CardViewController()
func addCardAsChild() { // add the child VC to the parent VC
self.addChild(self.cardViewController)
}
func triggerAlert() {
let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
alertController.addTextField(configurationHandler:
{(_ textField: UITextField) -> Void in //txtview customization
})
let addAction = UIAlertAction(title: "Add", style: .default) { _ in
guard let sectionName = alertController.textFields?.first?.text else { return }
self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
}
alertController.addAction(addAction)
self.present(alertController, animated: true, completion: nil)
}
}
class CardViewController: UIViewController, NewSectionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
guard let homeViewController = self.parent as? HomeViewController else { return }
homeViewController.sectionNameDelegate = self
}
func sendSectionName(name: String) {
print("received name:\(name)") // This line of code is never called
}
}
I think the delegate method is getting called but for the internal HomeViewController you're making in the ChildViewController viewDidLoad method. It looks like you're expecting the method to get called on a different object. I would remove that code from viewDidLoad and set the sectionNameDelegate in HomeViewController

why is bringSubviewToFront() only working for panning, not tapping?

view.bringSubviewToFront(tappedView)
is working when I drag (pan) views but not when I tap them. My issue is that when I have one view layered over the other, I want the bottom view to come to the front when tapped. Currently it will only come to the front when dragged. Do I need some additional code to do this? Thanks.
Here's an excerpt from my code for more context:
#objc func didPan(_ recognizer: UIPanGestureRecognizer) {
let location = recognizer.location(in: self.view)
switch recognizer.state {
case .began:
currentTappedView = moviePieceView.filter { pieceView -> Bool in
let convertedLocation = view.convert(location, to: pieceView)
return pieceView.point(inside: convertedLocation, with: nil)
}.first
currentTargetView = movieTargetView.filter { $0.pieceView == currentTappedView }.first
case .changed:
guard let tappedView = currentTappedView else { return }
let translation = recognizer.translation(in: self.view)
tappedView.center = CGPoint(x: tappedView.center.x + translation.x, y: tappedView.center.y + translation.y)
recognizer.setTranslation(.zero, in: view)
view.bringSubviewToFront(tappedView)
```
I had this same problem, I managed to solve it this way:
Add a gestureRecognizer to your view and put this in your code. Don't forget to set the delegate as well when attaching this to the code!
#IBAction func tappedView1(recognizer: UITapGestureRecognizer) {
view.bringSubviewToFront(myView)
}
Put this in your viewDidLoad:
let tap = UITapGestureRecognizer(target: self, action: #selector(tappedView1))
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)
If you want to do that from your panGesture check my question.
Thank you all. It worked when I wrote a second function in addition to didPan().
This is the additional code:
override func viewDidLoad() {
super.viewDidLoad()
configureLabel()
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:)))
view.addGestureRecognizer(panGestureRecognizer)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTap(_:)))
view.addGestureRecognizer(tapGestureRecognizer)
}
#objc func didTap(_ recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: self.view)
currentTappedView = moviePieceView.filter { pieceView -> Bool in
let convertedLocation = view.convert(location, to: pieceView)
return pieceView.point(inside: convertedLocation, with: nil)
}.first
guard let tappedView = currentTappedView else { return }
view.bringSubviewToFront(tappedView)
}
HOWEVER, I found out you can also just tick the "User Interaction Enabled" box in the Image View if you don't want to do it programmatically.

Why delegate event is not received swift?

I would like to pass data from EditPostViewController to NewsfeedTableViewController using delegates, but func remove(mediaItem:_) is never called in the adopting class NewsfeedTableViewController. What am I doing wrong?
NewsfeedTableViewController: UITableViewController, EditPostViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//set ourselves as the delegate
let editPostVC = storyboard?.instantiateViewController(withIdentifier: "EditPostViewController") as! EditPostViewController
editPostVC.delegate = self
}
//remove the row so that we can load a new one with the updated data
func remove(mediaItem: Media) {
print("media is received heeeee")
// it does't print anything
}
}
extension NewsfeedTableViewController {
//when edit button is touched, send the corresponding Media to EditPostViewController
func editPost(cell: MediaTableViewCell) {
let editPostVC = storyboard?.instantiateViewController(withIdentifier: "EditPostViewController") as? EditPostViewController
guard let indexPath = tableView.indexPath(for: cell) else {
print("indexpath was not received")
return}
editPostVC?.currentUser = currentUser
editPostVC?.mediaReceived = cell.mediaObject
self.navigationController?.pushViewController(editPostVC!, animated: true)
}
protocol EditPostViewControllerDelegate: class {
func remove(mediaItem: Media)
}
class EditPostViewController: UITableViewController {
weak var delegate: EditPostViewControllerDelegate?
#IBAction func uploadDidTap(_ sender: Any) {
let mediaReceived = Media()
delegate?.remove(mediaItem: mediaReceived)
}
}
The objects instantiating in viewDidLoad(:) and on edit button click event are not the same objects. Make a variable
var editPostVC: EditPostViewController?
instantiate in in viewDidLoad(:) with delegate
editPostVC = storyboard?.instantiateViewController(withIdentifier: "EditPostViewController") as! EditPostViewController
editPostVC.delegate = self
and then present it on click event
navigationController?.pushViewController(editPostVC, animated: true)
or
present(editPostVC, animated: true, completion: nil)
you can pass data from presenter to presented VC before or after presenting the VC.
editPostVC.data = self.data
I suggest having a property in NewsfeedTableViewController
var editPostViewController: EditPostViewController?
and then assigning to that when you instantiate the EditPostViewController.
The idea is that it stops the class being autoreleased when NewsfeedTableViewController.viewDidLoad returns.

NSTabViewController - How to create custom transition?

I have an NSTabViewController, and I want to create some custom transition.
I added some NSViewControllerTransitionOptions values and when transition method is called with my values, a custom animation should run.
Bellow is the intermediate code that I written until now. Animation run exactly how what I want, but there is a problem.
nextVC is not presented (I think). That controller should be first responder, after animation that is not respond to keyboard import.
override func transition(from fromViewController: NSViewController, to toViewController: NSViewController, options: NSViewControllerTransitionOptions = [], completionHandler completion: (() -> Void)? = nil) {
if options.contains(.analogToThemes) {
if let firstVC = fromViewController as? MBCustomizeController {
let nextVC = toViewController
let themesContainer = nextVC.view
themesContainer.setFrameOrigin(NSMakePoint(-250, -510))
var sketchContainer:NSView?
var panelsContainer:NSView?
firstVC.view.addSubview(themesContainer)
for item in firstVC.view.subviews {
if item.identifier == "sketchContainer" {
sketchContainer = item
}
if item.identifier == "customizePanlesContainer"{
panelsContainer = item
}
}
NSAnimationContext.runAnimationGroup({ context in
context.duration = animationDuration
themesContainer.animator().setFrameOrigin(NSMakePoint(0, 0))
sketchContainer!.animator().setFrameOrigin(NSMakePoint(sketchContainer!.frame.origin.x, 520))
panelsContainer!.animator().setFrameOrigin(NSMakePoint(panelsContainer!.frame.origin.x + panelsContainer!.frame.width , 0))
}, completionHandler: {
firstVC.dismiss(nil)
})
}
return
}
super.transition(from: fromViewController, to: toViewController, options: options, completionHandler: completion)
}
How can I present nextVC correctly?
Thanks.