Downcasting Any? to UIBarButtonItem - ios

override func prepare(for segue: UIStoryboardSegue, sender:
Any?) {
if segue.identifier == "detailSegue" {
let indexPath = tableView.indexPathForSelectedRow!
let card = cards[indexPath.row]
let detailTableViewController = segue.destination as! DetailTableViewController
detailTableViewController.card = card
detailTableViewController.picture = card.image
} else if segue.identifier == "addEditSegue" {
let addEditTableViewController = segue.destination as! AddEditTableViewController
let buttonPressed = sender as? UIBarButtonItem
if buttonPressed == cardsAddButton {
addEditTableViewController.isNewCard = true
} else {
addEditTableViewController.isNewCard = false
}
}
}
Hi, I am new to Swift. I need to perform the same segue by either tapping a UIBarButtonItem (cardsAddButton) or by tapping on cells of a UITableView. Using print statements I found that buttonPressed is nil when I tap cardsAddButton. Why? How should I check what was the sender?

You – the developer – should know who the sender of prepare(for is. There are only three possibilities:
If the segue is connected to the table view cell in Interface Builder then the sender is the UITableViewCell.
If the segue is connected to the view controller in Interface Builder then the sender is the UIViewController.
If performSegue is called in code then the sender is whatever you passed in the sender parameter (including nil).
Your code can work only if you call performSegue in the IBAction of the button and pass the button instance as sender
#IBAction func addCard(_ sender : UIBarButtonItem)
{
self.performSegue(withIdentifier:"addEditSegue", sender: sender)
}

Related

swift button press action loads tableview controller twice

I have a MeterTableviewController connected to two tableview controllers with two segues. The first segue LocationListSegue is connected from a button on the MeterTableviewController directly to the LocationListTableViewController. Another segue MetersListSegue connected from the top of the MeterTableViewController to the
MeterListTableviewController.
When I press on the location button, the LocationListTableViewController gets loaded twice.
I thought it is because I was calling it twice: once from the button IBAction and another time on Prepare, so I commented the code from Prepare, but it still loads it twice.
However the MeterListTableViewController gets loaded only once.
I dont know why the button press loads the controller twice. Can someone tell me?
#IBAction func chooseLocation(_ sender: Any) {
self.performSegue(withIdentifier: "LocationListSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
/*
if segue.identifier == "LocationListSegue"{
let viewController:LocationListTableViewController = segue.destination as! LocationListTableViewController
}
*/
if segue.identifier == "MetersListSegue"{
let viewController2:MeterListTableViewController = segue.destination as! MeterListTableViewController
}
}
You have added a segue as well as segue action from button, remove one of them
Remove story board segue and change your code with my code. This is enough for you.
#IBAction func chooseLocation(_ sender: Any) {
let tableViewController = self.storyboard?.instantiateViewController(withIdentifier: "your identifier") as! MeterListTableViewController
self.navigationController?.pushViewController(tableViewController, animated: true)
}
If you want to use segue remove IBAction for UIButton and write this code.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "LocationListSegue"{
let viewController:LocationListTableViewController = segue.destination as! LocationListTableViewController
} else if segue.identifier == "MetersListSegue"{
let viewController2:MeterListTableViewController = segue.destination as! MeterListTableViewController
}
}

Determining the cell from a UILongPressRecognizer for a segue

I'm having a slight problem with a basic checklist app I'm building.
On a regular tap of a table view cell, I segue to my NewTaskViewController using prepare(for segue):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AddTask" {
let nav = segue.destination as! UINavigationController
let newTaskVc = nav.topViewController as! NewTaskViewController
newTaskVc.delegate = self
newTaskVc.managedContext = managedContext
I also have perform a segue on a UILongPressGestureRecognizer that I added to my cell. Long pressing should segue to the same NewTaskViewController but this time adding the cell's TaskItem to its taskToEdit property
} else if segue.identifier == "EditTask" {
let nav = segue.destination as! UINavigationController
let editTaskVc = nav.topViewController as! NewTaskViewController
editTaskVc.delegate = self
editTaskVc.managedContext = managedContext
editTaskVc.taskToEdit = ?
As I'm using a UILongPressRecognizer, I'm struggling to work out how I determine the index path of the cell long-pressed so I can pass the correct item through.
Essentially, how do I identify a table view cell from a gesture recognizer?
Thanks in advance!
Well could you try something like this inside your handling function?
if longPressGestureRecognizer.state == UIGestureRecognizerState.Began {
let touchPoint = longPressGestureRecognizer.locationInView(self.view)
if let indexPath = tableView.indexPathForRowAtPoint(touchPoint) {
// Your Stuff
}
}

Button state info

The question is similar to "how to pass data from different viewController" but in this case I need another information, I know how to pass the data from one viewController to another but I don't know how to tell to the second viewController a specific state of an object that is in the first view. In my case I have some buttons in the first view that go in.
button.isHidden = true
after the tap, I want to tell to the second viewController which buttons have been tap, maybe I've to create a variable that represents the status of the button, but I don't know how to do, someone can help me?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToLast" {
guard let vc = segue.destination as? FinalClass else { return }
let guest = segue.destination as! FinalClass
if let user = sender as? User {
}
}
}
where User can be something like
struct User {
var button1 = Button1 tapped
var button2 = Button2 tapped
ecc.
}
Let suppose you have two viewControllers - FirstViewController and SecondViewController.
So First,
Let Declare two Arrays in FirstViewController and SecondViewController something like -
var tappedButtonsArray = NSMutableArray() // In 'FirstViewController'
AND
var previousViewTappedButtonsArray = NSMutableArray() // In 'SecondViewController'
And here is my code to add | remove tapped buttons to | from tappedButtonsArray in FirstViewController -
#IBAction func btnTapped(_ sender: UIButton) { // Single action for all buttons
if (tappedButtonsArray.contains(sender)){
tappedButtonsArray.remove(sender) // Remove previous tapped button on unselect
}
else{
tappedButtonsArray.add(sender) // Add tapped button on select
}
}
And Here is your perform segue method:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToLast" {
guard let secondViewController = segue.destination as? SecondViewController else { return }
secondViewController.previousViewTappedButtonsArray = tappedButtonsArray
}
}
I've done with a simple array concept without any model, so that you can understand the follow. I hope it'll help you to start with.

Changing label text of second ViewController upon clicking button in first ViewController

I'm new to Swift and to iOS Development. I currently have 2 ViewControllers, a button in the first and a label in the second one. I've connected the first button to the second ViewController and the transition works.
Now, when I try changing the label's text I get the error:
fatal error: unexpectedly found nil while unwrapping an Optional
value
.
Here you find my prepare function in the first ViewController:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! SecondViewController
vc.secondResultLabel.text = "Testing"
}
}
Can it be that the label in the second ViewController is somehow protected ?
Thanks for the help
You need to pass the String to the SecondViewController instead of directing setting it, as the UILabel has not been created yet.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! SecondViewController
vc.secondResultLabelText = "Testing"
}
}
And in your SecondViewController viewDidLoad method set the UILabel to be the string
var secondResultLabelText : String!
override func viewDidLoad() {
secondResultLabelText.text = secondResultLabelText
}
add a string variable in the second view controller
var labelText: String!
in second view controller also (in viewDidLoad)
self.secondResultLabel.text = self.labelText
then first view controller prepare for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! SecondViewController
vc.labelText = "Testing"
}
}
this is because second view controller's UILabel Outlet is not being initialized yet in prepare for segue
Rikh's answer is the same, both his answer and mine are the same
Welcome aboard :)
Your problem is that your SecondViewController, and more specifically vc.secondResultLabelText is not initiated when you call prepare, so secondResultLabel is actually nil at that time.
You need to add a variable to your SecondViewController like so:
var labelText: String = ""
And then set that value instead:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! SecondViewController
vc.labelText = "Testing"
}
}
In viewWillAppear or viewDidLoad on your SecondViewController you can then use that value for your secondResultLabelText which is now ready, connected, and won't crash
secondResultLabelText.text = labelText
Hope that helps.
First take a global variable in SecondViewController... eg I took "secondViewControllerVariable". Then get the text you want to display in your SecondViewController.
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "mySegue"
{
let vc = segue.destination as! SecondViewController
vc.secondViewControllerVariable = "Your string you get in FirstViewController"
}
}
And then in your SecondViewController, in viewDidLoad method set the UILabel to be the string
var secondViewControllerVariable : String! // You have to declare this first in your SecondViewController Globally
override func viewDidLoad()
{
vc.secondResultLabelText.text = secondViewControllerVariable
}
That's it. Happy Coding.

Prepare for Segue in Swift with Sender

I am trying to pass a UIColor to another viewController via a "show" segue so that the color of the background can match that of the color button that was selected. I have this bit of code that prints the buttons sender tag but it is not performing that segue.
What am I doing wrong? I have never worked with sender tags before so it could be something silly but I am not sure.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toQuiz" {
if sender?.tag == 1 {
let viewController:ViewController = segue.destinationViewController as! ViewController
let color = UIColor.blueColor()
viewController.passedColor = color
} else if sender!.tag == 2 {
let viewController:ViewController = segue.destinationViewController as! ViewController
let color = UIColor.greenColor()
viewController.passedColor = color
} else if sender!.tag == 3 {
let viewController:ViewController = segue.destinationViewController as! ViewController
let color = UIColor.yellowColor()
viewController.passedColor = color
}
}
}
#IBAction func athButtonTapped(sender: AnyObject) {
let athleteQuiz = sender as! UIButton
print("Button \(athleteQuiz.tag) was pressed!")
}
#IBAction func actorButtonTapped(sender: AnyObject) {
let actorQuiz = sender as! UIButton
print("Button \(actorQuiz.tag) was pressed!")
}
#IBAction func musicButtonTapped(sender: AnyObject) {
let musicQuiz = sender as! UIButton
print("Button \(musicQuiz.tag) was pressed!")
}
This is the storyboard layout - they are all connected properly and the identifier for the segue matches that in the storyboard.
Some things to check:
Does the left view controller have your class assigned to it in IB?
Is anything actually triggering the segue? Neither of your button actions contain a call to performSegueWithIdentifier(_:sender:)
Also, this is a very dangerous block of code; you should not be force-unwrapping sender like that. Instead, consider doing something like this:
guard let id = segue.identifier else { return } // Bail if there isn't a segue ID.
if id == "toQuiz" {
guard let tag = (sender as? UIView)?.tag else { return } // Bail if we can't get a tag.
// Continue examining the tag.
}

Resources