Swift 2/Xcode 7: unrecognized selector sent to instance - swift2

My function is this and it is called with a "done" UIBarButtonItem.
#IBAction func done(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
I have read multiple other questions/answers about a deleted instance or an old/extra connection in the Interface Builder or in the View Controller code. However, I only have this one function all properly connected without any extra lingering connections. How do I get rid of the "unrecognized selector sent to instance" error
Thanks in advance!

With the information provided in the question I suspect
There is unwanted connection left. To see that you can do:
1) Go to the IB and select the button.
2) Right click on the button and see all the actions. If you see any unwanted action delete it and try running again.
You can also do it programmatically
Set the target for UIBarButtonItem like this
var b = UIBarButtonItem(
title: "Continue",
style: .Plain,
target: self,
action: "sayHello:"
)
func sayHello(sender: UIBarButtonItem) {
}
If you dont want any parameters in the sayHello function, you can do it
var b = UIBarButtonItem(
title: "Continue",
style: .Plain,
target: self,
action: "sayHello"// Remove the colon
)
func sayHello() {
}
Let me know if it works for you

Related

Prevent UISegmentedControl from sending action method automatically

I'm programming an app for tvOS and am using a UISegmentedControl. My issue is that as I'm scrolling through items, it sends its action method as soon as I remain on an item for a second or two. I would like to disable this behaviour and rather fire the action only if user clicks it.
Does anyone know how to do it?
I had the same problem with my tvOS app and solved with this:
#IBOutlet weak var searchSegmentedControl: UISegmentedControl!
override func viewDidLoad() {
let tap = UITapGestureRecognizer(target: self, action: #selector(didClickSegmentedSearchButton))
tap.numberOfTapsRequired = 1
view.addGestureRecognizer(tap)
}
func didClickSegmentedSearchButton() {
switch searchSegmentedControl.selectedSegmentIndex {
case 0:
// Restaurant
case 1:
// Hotel
case 2:
// Attraction
case 3:
// Shopping
default:
// Unknown
}
}

Do something on button click inside of footer in a tableView

I have a tableView that has a header, a footer and a prototype cell for dynamic purposes. I have a Sign Out button in the footer but can't figure out how to get it linked up with a function. I setup a segue to go back to a login page but I want an alert box to ask for confirmation first so I need to somehow call a function.
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerCell = tableView.dequeueReusableCellWithIdentifier("Footer") as! MenuTableViewCell
footerCell.logout.targetForAction("logOutButtonClicked", withSender: self)
return footerCell
}
This is what I have now, but upon click it crashes and gives me
'NSInvalidArgumentException', reason: '-[.MenuTableViewCell logOutButtonClick:]: unrecognized selector sent to instance 0x7ffce28615d0'
I have a function called logOutButtonClicked that looks like this...
func logOutButtonClicked(){
let alertView = UIAlertController(title: "Log Out?", message: "Are you sure you want to Log Out?", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil))
alertView.addAction(UIAlertAction(title: "Log Out", style: .Default, handler: {(alertAction) -> Void in
self.logOut()}))
presentViewController(alertView, animated: true, completion: nil)
}
func logOut(){
performSegueWithIdentifier("goHome", sender: self)
}
Edit:
I've also tried footerCell.logout.addTarget(self, action: "logOutButtonClicked", forControlEvents: .TouchUpInside)
but that gives the same error as well.
You have to create a function called "logOutButtonClicked" since you specified by adding the targetForAction, it would look something like this:
func logOutButtonClicked() {
}
I managed to fix this problem by erasing all of the events and outlets corresponding to the button (the ones you find when you right click on it) and then rewriting the function like so...
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerCell = tableView.dequeueReusableCellWithIdentifier("Footer") as! MenuTableViewCell
footerCell.logout.addTarget(self, action: "logOutButtonClicked", forControlEvents: .TouchUpInside)
return footerCell
}

Don't know why the switch control always send false Value

I make a simple WKInterface with a switch control and make a function for that switch to show up the value of switch like this:
I don't know why when test the switch,the result I received always false? please explain and show me how to fix. As I thought the out put of that switch will change from false to true and move on like that.. What's wrong in here? or the Xcode's bug with switch?
Here, instead of passing value of type Bool, pass it as a UISwitch:
#IBAction func testSwitchPressed(value: UISwitch) {
println(value.on)
}
This will correctly tell if if your switch is on or off.
This is great because you can use Control Flow as well with this:
#IBAction func testSwitchPressed(value: UISwitch) {
//println(value.on)
if value.on {
println("The switch has been enabled!")
//cool features here
} else {
println("The switch has been disabled!")
//other cool features here
}
}
Good luck!
Try this:
First declare outlet for switch like this:
#IBOutlet weak var mySwitch: UISwitch!
In viewDidLoad implement listener (target-action):
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mySwitch.addTarget(self, action: "switchChangedValue:", forControlEvents: UIControlEvents.ValueChanged)
}
Declare this function where you will get response every time switch value is changed:
func switchChangedValue(sender:UISwitch){
if sender.isKindOfClass(UISwitch){
if sender.on {
println("Switch is ON")
println("\(sender.on)")
} else {
println("Switch is OFF")
println("\(sender.on)")
}
}
}
the IBAction function passes the UIElement which triggered the action.
So use something like this
#IBAction func testSwitchPressed(sender : UISwitch)
{
println(sender.on)
}
If you press CTRL and drag the mouse in the InterfaceController source code, the following function is automatically added:
-(IBAction)TapOnSwitch:(BOOL)value
{
}
And value is correct.
This is valid if you want check the value when the user change the value of the switch.

Xcode_OSX/Swift_NSPopUpButton.

I am incredibly new to this, so please keep that in mind!
I've been at this all night, watched countless videos/haunted
countless forums...I can't find one single answer!
I am trying to make a basic popup menu in Swift/OSX What I need to figure out is:
How can I add more than the 'three items' to this menu
Whatever is selected in the popup, for that info to send an integer
value to another number.
I very much would appreciate your help, Thanks.
A NSPopupButton is a container for a bunch of NSMenuItem objects so to add an item you can use
func addItemWithTitle(_ title: String!)
The NSMenuItem gets constructed for you by the call.
and as you may wish to start from scratch you can use
func removeAllItems()
To clean existing items from the button.
There are also other methods around moving and removing menu items from the button.
A NSPopupButton is-a NSControl so you can use var action: Selector to set the action sent when an item is selected and var target: AnyObject! to control which object receives the message. Or just wire it up in Interface Builder.
protocol FooViewDelegate{
func itemWithIndexWasSelected(value:Int)
}
class FooViewController: NSViewController {
#IBOutlet weak var myPopupButton: NSPopUpButton!
var delegate: FooViewDelegate?
let allTheThings = ["Mother", "Custard", "Axe", "Cactus"]
override func viewDidLoad() {
super.viewDidLoad()
buildMyButton()
}
func buildMyButton() {
myPopupButton.removeAllItems()
myPopupButton.addItemsWithTitles(allTheThings)
myPopupButton.target = self
myPopupButton.action = "myPopUpButtonWasSelected:"
}
#IBAction func myPopUpButtonWasSelected(sender:AnyObject) {
if let menuItem = sender as? NSMenuItem, mindex = find(allTheThings, menuItem.title) {
self.delegate?.itemWithIndexWasSelected(mindex)
}
}
}
All the button construction can be done in Interface Builder rather than code too. Remember that you can duplicate items with CMD-D or you can drag new NSMenuItem objects into the button.

(NSMenuItem): missing setter or instance variable

I am encountering a strange error:
2015-04-02 12:20:14.642 test[21167:257788] Failed to connect
(testApp) outlet from (test.AppDelegate) to (NSMenuItem): missing
setter or instance variable
inserted id: 122
I occured when a added a menuItem to a menu and connected a function to it.
I do not know what the Problem is. The app works fine but i don't think it is a smart idea to ignore the error.
What is meant by setter or instance variable? Why is it needed?
UPDATE: Here is the relevant code:
import Cocoa
import Foundation
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
func applicationDidFinishLaunching(aNotification: NSNotification) {
let icon = NSImage(named: "statusIcon")
statusItem.image = icon
statusItem.menu = statusMenu
// Time for constant repeat
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerRepeat", userInfo: nil, repeats: true)
}
// Method to call the tracking core
func timerRepeat() {
//....
}
#IBAction func frontEnd(sender: NSMenuItem) {
var targetURL : String = NSBundle.mainBundle().resourcePath!
targetURL = targetURL + "/" + "front.app"
let workspace = NSWorkspace()
workspace.launchApplication(targetURL)
}
#IBAction func menuClicked(sender: NSMenuItem) {
NSApplication.sharedApplication().terminate(self)
}
}
You have a broken outlet in your xib file. Usually it happens when you set up an outlet to ivar or property which is later deleted or renamed not using Xcode's rename feature.
Also make sure that your custom view or view controller class is added to your target. (Project => Target Name => Build Phases => Compile Sources). It's possible that a file is in your project but not your target.
This happens because you at one point created an #IBOutlet for a storyboard element. You then later removed the code (reference) from your swift file.
I created an example where I create two extra #IBOutlets (I named them 'correctField' and 'incorrectField'- both are incorrect though) and connected them from my storyboard to my swift file.
I then removed the code from my swift file. This generates the log as shown in the following figure :
To remove this kind of log message, you can do the following:
Go to the 'storyboard' and select the storyboard elements you created connections (#IBOutlets) from.
Open the 'connection inspector' as showed in the figure below
Remove the Referencing Outlets which are incorrect (in my case it is the 'correctField' and 'incorrectField')
Done
This was done in xCode 11

Resources