Swift gives me "unrecognized selector sent to instance 0x7fe985706fd0" after pressing a button - swift

The code is:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func testButton(_ sender: UIButton) {
print("Hello")
}
}
It gives me the error "unrecognized selector sent to instance 0x7fe985706fd0" when I press the button.

Check View Controller as shown in image
This may be due to the following reasons:-
First if _ is missing before sender:-
#IBAction func testButton( sender: UIButton):-Wrong
#IBAction func testButton(_ sender: UIButton):-Correct
It may be possible that your storyboard is linked to another view controller, not with the required view controller.
For this select your storyboard and check whether the correct view controller is linked to your storyboard.
It may be possible your button connection is removed.

Related

Why doesn't performSegue() call shouldPerformSegue()

Quite new to programming in Swift and mobile development in general. I am trying to use performSegue() and control it without if-else statements. I made a google search how to use override func shouldPerformSegue() and tried to implement it in different ways but none of them solved my situation. Here I need to segue to Yellow or Green views if the switch is on using corresponding buttons. Even if I made return false, the function does not cancel the segue to happen. What is the reason of this behaviour and how can I fix it? Many thanks.
class ViewController: UIViewController {
#IBOutlet var segueSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func yellowButtonTapped(_ button: UIButton) {
performSegue(withIdentifier: "Yellow", sender: nil)
}
#IBAction func greenButtonTapped(_ button: UIButton) {
performSegue(withIdentifier: "Green", sender: nil)
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// return segueSwitch.isOn
return false
}
}
shouldPerformSegue does not get called if you use performSegue(withIdentifier: in code. This function only get called if the segue is triggered from storyboard.
You can easily test this by adding 2 Buttons to a ViewController in storyboard one with the storyboard segue and one with an IBOutlet to a new ViewController. Then add a print statement to shouldPerformSegue. In the Button outlet call performSegue. Only the first button performing the segue from storyboard will print to the console.
And additionally you don´t need it. Any validation you would perform in shouldPerformSegue can be done in the ...ButtonTapped function:
#IBAction func yellowButtonTapped(_ button: UIButton) {
if validateSegue(){
performSegue(withIdentifier: "Yellow", sender: nil)
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
validateSegue()
}
func validateSegue() -> Bool{
......
}
This is deliberate and makes perfect sense. shouldPerformSegue lets you prevent an automatically triggered segue in case you don't want it performed. But if you didn't want a manual segue performed, all you had to do is nothing — don't say performSegue in the first place.
and control it without if-else statements
If-else is exactly how to control it.

How to disable a button within a anyObject Button in swift

Ok so I want to be able to disable the button within itself. So when I press the button it will disable itself.
import UIKit
class ViewController: UIViewController {
#IBOutlet var buttons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func but(_ sender: AnyObject) {
//this code doesn't seem to work at all, and I don't know why
(sender as AnyObject).isEnabled = false
}
}
It gives me an error message when ever I try to do this "Cannot assign to immutable expression of type '#lvalue Bool?'"
So is there a different way I can disable this button
Presumably, you've hooked up this IBAction in Interface Builder to a UIButton. So, you can change your function signature to:
#IBAction func but(_ sender: UIButton) {
sender.isEnabled = false
}
AnyObject doesn't have a property called isEnabled, which is why your previous code failed.
within the button I use this code
#IBAction func but(_ sender: AnyObject) {
var disableMyButton = sender as? UIButton
disableMyButton?.isEnabled = false
}

View Controller shows as pop-up

I want a normal segue, so no pop-up. But when I push the button to go to the next ViewController, it shows as ab pop-up. The buttons to the next ViewController is in a different storyboard than the ViewController I'd like to go to.
This is the code of the first ViewController:
import UIKit
//some other code
class LoginViewController: UIViewController {
//some other code
override func viewDidLoad() {
super.viewDidLoad()
//some other code
}
#objc private func ProceedTapped(){
//Door naar storyboard van de daadwerkelijke app
print("Proceed clicked")
performSegue(withIdentifier: "goToAppIdentifier", sender: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
}
And this is the code of the ViewController I'd like to go to:
import UIKit
class HomeScreen: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("Home has loaded")
}
}
The kind of the segue of the "Storyboard Segue" is "Show (e. g. push)"
You just have to go to story board select the 2nd view controller and change presentation style to "Full Screen". Please check below image for reference

unwind segue not triggering

I have been learning swift and have made the foundation of most of my app. I have the following storyboard
app storyboard
Everything works fine. For example, I have an unwind segue on the add course view controller that triggers when you press save and you are returned to the 'your courses' view controller.
When you are on the my courses view controller, you can select a course and the topics are displayed, you can then select a topic and you are taken to an update score view controller, this all works fine.
However, my problem is this. I want to make it so that when you select save in the updatescore view controller, an unwind segue is triggered (the same as in the add course) and you are returned to the list of topics in the topics view controller.
However, I have followed many tutorials and obviously got it working before. (My action method for the unwind segue is in the correct topics view controller) but when i press save, the unwind segue is not returning me to the topics view controller.
Could anyone suggest a reason for this? I have spent a lot of time trying to find an answer and gone through many tutorials but have not managed to solve it.
I have also included a screen shot of the connections of the triggered segues for my save button to show that it is set up. Showing triggered segue for save button
i have the following code in the update score view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
print("save button selected")
}
}
But even this is not getting triggered when I click on save.
Many thanks
UPDATE:
After following Ronatorys advice My view controller for the update score is as follows but it is still not working:
import UIKit
class UpdateScoreTableViewController: UITableViewController {
#IBOutlet weak var topicGettingUpdated: UITextField!
#IBOutlet weak var newScore: UITextField!
#IBOutlet weak var saveButton: UIBarButtonItem!
var index:Int?
var Topics:[String]!
var TopicToUpdate:String?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let uiBarButtonItem = sender as? UIBarButtonItem else {
print("There is no UIBarButtonItem sender")
return
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 && indexPath.row == 0 {
newScore.becomeFirstResponder()
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
But the prepare for segue is not even getting triggered.
Like Craig in the comments said, it's not that easy to find the problem. So I just build a simple app where you can follow the steps as guide and see if you forgot something to setup the functionality right. Hope it will help you. Note: Code is in Swift 3.0, but should be easy to adopt to 2.*
1. Storyboard with two View Controllers:
2. Declare the action method for the unwind segue in the FirstViewController.swift:
class FirstViewController: UIViewController {
// action method for the unwind segue
#IBAction func updateScore(_ segue: UIStoryboardSegue) {
print("Back in the FirstViewController")
}
}
3. Connect the Save button in the Storyboard with the action method (with ctrl + drag):
4. Connect your Save button with the SecondViewController.swift file, to use it for checking in your prepareSegue method (with ctrl + drag):
5. Add the prepare(for:sender:) method to your SecondViewController.swift:
class SecondViewController: UIViewController {
#IBOutlet weak var saveButtonPressed: UIBarButtonItem!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// check safely with guard that your save button is the sender and you can use it
// if not print message
guard let uiBarButtonItem = sender as? UIBarButtonItem else {
print("There is no UIBarButtonItem sender")
return
}
// check if you selected the save button
if saveButtonPressed == uiBarButtonItem {
print("save button selected")
}
}
}
Result:
The sample app you can find here
I did not manage to get the unwind segue to work but instead used
navigationController!.popViewControllerAnimated(true)
as a work around and this works fine.

Need to free memory after Modal Segues, but I need both my Segues to pass data from A to B and B to A

I am making a game for iOS with SpriteKit.
I have 2 Viewcontrollers. One is the GameViewController and the other one is the MenuViewController. Let's call them A and B respectively.
When the player dies, a function is called in GameScene.swift that launches a modal "Lost" Segue to B. There, the player can restart the game or buy a life and a "Back" Segue is called to A.
I need to dismiss the additional Views that get created each time I call a segue.
Problem is: I need the "Lost" Segue to send data about the Score to View B and I need the "Back" Segue to send data to View A about wether or not the player used a life.
I have implemented all this. But now I need to find how to dismiss old views that keep eating the device's memory, thus leading to lag and crash.
I have googled for hours and hours. No solution was adapted to my situation.
The solutions I found either caused my app to bug, data not to be passed or views not to be generated.
I will not add code here since there is a LOT. But I am sure the answer is actually really easy, just not for a beginner like me.
I think a possible solution would be an unwind segue from B to A ?
But do unwind segues pass data along ?
Moreover, I found no answer I could understand on how to use an unwind segue.
I exhausted all my possibilities. Stack Exchange is my last chance.
You definitely should use an unwind segue to return to the previous viewController, otherwise as you have found your memory usage increases until your apps quits.
I created the following example from your description. It uses a standard segue to move from the GameViewController to the MenuViewController and it uses an unwind segue to move from the MenuViewController back to the GameViewController.
The GameViewController has a Player Dies UIButton, a UITextField for entering a score, and a UILabel for displaying the lives.
The MenuViewController has a UILabel for showing the score, a Buy a Life UIButton for adding lives, and a Restart UIButton for returning to the GameViewController.
Here's the code:
GameViewController.swift
import UIKit
class GameViewController: UIViewController {
#IBOutlet weak var scoreTextField: UITextField!
#IBOutlet weak var livesLabel: UILabel!
var lives = 3
func updateLivesLabel() {
livesLabel.text = "Lives: \(lives)"
}
override func viewDidLoad() {
super.viewDidLoad()
updateLivesLabel()
}
// This is the function that the unwind segue returns to.
// You can call it anything you want, but it has to be in
// the viewController you are returning to, it must be tagged
// with #IBAction and it must take a UIStoryboardSegue as its
// only parameter.
#IBAction func returnFromMenu(segue: UIStoryboardSegue) {
print("We're back in GameViewController")
// Update the lives label based upon the value passed in
// prepareForSegue from the MenuViewController.
updateLivesLabel()
}
#IBAction func goPlayerDies(sender: UIButton) {
lives--
self.performSegueWithIdentifier("Lost", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Lost" {
let destinationVC = segue.destinationViewController as! MenuViewController
destinationVC.score = Int(scoreTextField.text ?? "") ?? 0
destinationVC.lives = lives
}
}
}
MenuViewController.swift
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var score = 0
var lives = 0
override func viewDidLoad() {
super.viewDidLoad()
scoreLabel.text = "Score: \(score)"
}
#IBAction func buyLife(sender: UIButton) {
lives++
}
#IBAction func goRestart(sender: UIButton) {
self.performSegueWithIdentifier("Back", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Back" {
let destinationVC = segue.destinationViewController as! GameViewController
destinationVC.lives = lives
}
}
}
This is how you wire up the forward segue to be called programmatically:
Control-drag from ViewController icon to the MenuViewController:
Select Present Modally from the pop-up:
Click on the segue arrow between the viewControllers and give it an identifier in the Attributes Inspector:
This is how you wire up the unwind segue to be called programmatically:
Control-drag from ViewController icon to Exit icon:
Choose returnFromMenu from pop-up:
Click on the Unwind Segue in the Document Outline and give it the identifier "Back" in the Attributes Inspector on the right:
Alternate Answer
Instead of using segues, you can present and dismiss viewControllers manually. The advantage for your app is that the MenuViewController will be allocated only once and will persist for the life of the app. This same viewController will be presented and dismissed repeatedly, but it will not be deallocated which I suspect is leading to your crashes.
The GameViewController will be the initialViewController that is created by the Storyboard. The MenuViewController will be loaded in viewDidLoad of the GameViewController.
To make this work, you need to add an identifier to the MenuViewController so that it can be instantiated by name. Click on the MenuViewController in the Storyboard and set its Storyboard ID in the Identity Inspector:
Here is the code. Note that all mention of segues is gone. Note how viewWillAppear is used to update the viewControllers.
GameViewController.swift
import UIKit
class GameViewController: UIViewController {
#IBOutlet weak var scoreTextField: UITextField!
#IBOutlet weak var livesLabel: UILabel!
var menuViewController: MenuViewController?
var lives = 3
func updateLivesLabel() {
livesLabel.text = "Lives: \(lives)"
}
override func viewDidLoad() {
super.viewDidLoad()
menuViewController = self.storyboard!.instantiateViewControllerWithIdentifier("MenuViewController") as? MenuViewController
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateLivesLabel()
}
#IBAction func goPlayerDies(sender: UIButton) {
lives--
menuViewController?.score = Int(scoreTextField.text ?? "") ?? 0
menuViewController?.lives = lives
self.presentViewController(menuViewController!, animated: true, completion: nil)
}
}
MenuViewController.swift
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var score = 0
var lives = 0
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
scoreLabel.text = "Score: \(score)"
}
#IBAction func buyLife(sender: UIButton) {
lives++
}
#IBAction func goRestart(sender: UIButton) {
let destinationVC = self.presentingViewController as! GameViewController
destinationVC.lives = lives
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}