Menu
  • HOME
  • TAGS

How to delete SKShapeNode in Swift

Tag: xcode,swift,sprite-kit

I'm making a SpriteKit project where one game screen needs to allow the user to draw on the screen. I want to have a "delete all" button and an "undo" button. However, I can't find out how to delete a path anywhere online. Here's how I'm drawing my lines:

var pathToDraw:CGMutablePathRef!
var lineNode:SKShapeNode!

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    let touch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    pathToDraw = CGPathCreateMutable()
    CGPathMoveToPoint(pathToDraw, nil, touchLocation.x, touchLocation.y)

    lineNode = SKShapeNode()
    lineNode.path = pathToDraw
    lineNode.strokeColor = drawColor
    self.addChild(lineNode)
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

    let touch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    CGPathAddLineToPoint(pathToDraw, nil, touchLocation.x, touchLocation.y)
    lineNode.path = pathToDraw   
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {}

But now the problem is how can I delete them? I have tried lineNode.removeFromParent() but it doesn't work. Any ideas?

Best How To :

You can keep track of the SKShapeNodes you draw on the screen in an array. First create a property shapeNodes

var shapeNodes : [SKShapeNode] = []

Add each lineNode to the shapeNodes in touchesBegan

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    //Your code
    shapeNodes.append(lineNode)
}

On pressing delete all button you loop through the shapeNodes array and remove them one by one.

func deleteAllShapeNodes() {

    for node in shapeNodes
    {
        node.removeFromParent()
    }
    shapeNodes.removeAll(keepCapacity: false)
}

For undo, you just have to delete the last node in the shapeNodes array.

 func undo() {
    shapeNodes.last?.removeFromParent()
    shapeNodes.removeLast()
 }

iOS Keyboard “Done” button load action

ios,swift,cocoa-touch

When the "Return Key" (or "Done") button is tapped, the delegate of your textfield will receive a set of callbacks including textFieldShouldEndEditing:, and textFieldDidEndEditing:. To respond to these, implement a UITextFieldDelegate and execute your action there, i.e. call loginActionButton in one of the delegate methods. Relevant Documentation: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/#//apple_ref/occ/intfm/UITextFieldDelegate/textFieldDidEndEditing:...

How can I fix crash when tap to select row after scrolling the tableview?

ios,xcode,swift,uitableview,tableviewcell

Because you are using reusable cells when you try to select a cell that is not in the screen anymore the app will crash as the cell is no long exist in memory, try this: if let lastCell = self.diceFaceTable.cellForRowAtIndexPath(lastIndexPath) as! TableViewCell{ lastCell.checkImg.image = UIImage(named: "uncheck") } //update the data...

Swift Singleton not Working

swift,singleton

If you use this method of singletons, to actually access the singleton you need to use DataWarehouse.sharedData, instead of DataWarehouse(), when you are 'constructing' the datawarehouse object within the other classes. At the moment you never actually access sharedInstance. If you are using Swift 1.2 and prefer, you can use...

looping variable in swift

swift,for-loop,uiimage

You don't need to create a new variable for each image, try this: for var i = 1; i < 8; i++ { images.append(UIImage(named: "image\(i)")) } This loop will create an array with 8 images without create the variables image1 to image8. I hope that help you!...

How to get time difference based on GMT on Swift

ios,swift

I think your problem is that you are using a calendar with an unset time zone. Your calculation of adding 60*60*24*2 to the current time does not account for the two days when some timezones change to and from daylight savings time. Those days are 23 and 25 hours long....

Implementing Applovin Ads with Swift & SpriteKit

ios,swift,applovin

You likely need to enable "Test Mode" for your app in the AppLovin dashboard in order to force test ads to serve for your area. Please send any questions to [email protected] for further assistance.

iOS 9 not opening Instagram app with URL SCHEME

ios,swift,swift2,ios9

iOS 9 has made a small change to the handling of URL scheme. You must whitelist the url's that your app will call out to using the LSApplicationQueriesSchemes key in your Info.plist. Please see post here: http://awkwardhare.com/post/121196006730/quick-take-on-ios-9-url-scheme-changes The main conclusion is that: If you call the “canOpenURL” method on a...

Cannot invoke method with argument list of type KeyType in Swift

swift,generics

I think that best solution for your case would be changing class declaration to: class EventDispatcher<U: EventDispatcherProtocol> { typealias KeyType = U.T And it will also simplify creation of the EventDispatcher with skipping the redundant type declarations: var dispatcher = EventDispatcher<CustomListener<CustomEvent>>() EDIT: Since the code was altered multiple times while...

What is the best practice add video background view?

ios,objective-c,swift,video

First of all, you have two main choices: use a imageView with a GIF or use a video for background with AVPlayer or MPMoviePlayerController. You can find a lot of example for both ways, here's a few: use a GIF for cool background video cover iOS In reply to your...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

ios,objective-c,swift,uitextfield,uilabel

You can register your textField for value change event: [textField addTarget: self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged]; and in textFieldDidChange function update your label: - (void)textFieldDidChange { label.text = textField.text; } The function shouldChangeCharactersInRange is needed more for taking desisions whether to allow upcoming change or not...

Omitting the return type in Swift closures

swift

I would not expect that example to have worked but it does In many cases, Swift can often infer types of variables and expressions. In this case, Swift looks at the value you're returning and can infer the type. If I modify that closure to specify a return type...

Obj-C Instance method returning a instanceType called from Swift - Function produces expected type 'UIImage!' error

ios,objective-c,swift

If you look at the method you have defined in Objective C image category, it is instance method and you are trying to call it using UIImage class in swift. You can basically use either one of the following two approaches, Either, self.backgroundImageView.image = self.someImage.applyDarkEffect() // notice the method does...

UITapGestureRecognizer sender is the gesture, not the ui object

ios,xcode,swift,uigesturerecognizer

You can get a reference to the view the gesture is added to via its view property. In this case you are adding it to the button so the view property would return you you the button. let button = sender.view as? UIButton ...

How to code a generic Swift class which stores a Generator of the same type

swift,generics

You have to use the generator type as the type placeholder G, and refer to its element type as G.Element: class MyGenericClass<G : GeneratorType> { var source : G var itemsProcessed : [ G.Element ] = [] init(source: G) { self.source = source } func getValue() -> G.Element? { let...

Build error after I localized Info.plist

ios,objective-c,xcode,swift,localization

Roll back those changes, add a InfoPlist.strings file to your project, localize it and then add the needed keys to it. For example: "CFBundleDisplayName" = "App display name"; "CFBundleName" = "App bundle name"; ...

Do I have to use both of these methods?

ios,swift,uitableview

No, you don't have to use both. Either you go with reloadCell technique or cell updates via beginUpdate and endUpdate. When you are reloading a particular row, internally table view system creates 2 cell and then blends in the new one with. You can remove the beginUpdates and endUpdates and...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

ios,swift,ios8,uiimagepickercontroller,ios8.3

Its orientation issues. UIImagePickerController wont support landscape mode.. Try this code source :: https://gist.github.com/mkeremkeskin/0ed9fc4a2c0e4942e451 - (BOOL)shouldAutorotate { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if ( orientation == UIDeviceOrientationPortrait | orientation == UIDeviceOrientationPortraitUpsideDown) { return YES; } return NO; } - (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown); } -...

How can I show ONLY the date (and not the time) using NSDateFormatter?

ios,iphone,swift

var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.locale = NSLocale(localeIdentifier: @"en_US") let d = NSDate() let s = dateFormatter.stringFromDate(d) ...

What's the equivalent of finally in Swift

swift,try-catch-finally

If you are thinking about the SWIFT 2.0 error handling to be the same thing as exception you are missunderstanding. This is not exception, this is an error that conforms to a protocol called ErrorType. The purpose of the block is to intercept the error thrown by a throwing function...

iOS Swift: Sound not playing on iPhone Simulator

ios,iphone,swift,audio,ios-simulator

You just need to move the declaration of your audioPlayer out of your method. Try like this: var audioPlayer:AVAudioPlayer! func playSound() { if let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") { audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) audioPlayer.prepareToPlay() audioPlayer.play() } } ...

How to add checkbox to uicollectionview in swift

swift,checkbox,uicollectionviewcell

Here is the example project available with checkbox cell. (objective - c) MyCell.m // A setter method for checked property - (void)setChecked:(BOOL)checked { // Save property value _checked = checked; // Update checkbox image if(checked) { self.checkBoxImageView.image = [UIImage imageNamed:@"Checked"]; } else { self.checkBoxImageView.image = [UIImage imageNamed:@"Unchecked"]; } } Your...

Unexpectedly found nil while unwrapping an Optional value - Plist

ios,swift,plist

Seems to be no error in your code, Check that the arrays in plist has the same naming as in your code might be mistaken something with keys. You can check that by right-click on plist and Open-as then choose source code Like : objectForKey("name") called <key>name</key> objectForKey("image") called <key>image</key>...

Can't figure out coder aDecoder: NSCoder

ios,xcode,swift

Your custom initializer cannot initialize the immutable property. If you want it to be immutable then, instead of creating a custom initializer, just initialize in one of the required or designated initializer. Like this, class AddBook: UIViewController { @IBOutlet weak var bookAuthor: UITextField! @IBOutlet weak var bookTitle: UITextField! let bookStore:...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active

ios,objective-c,swift

How about -searchBarTextDidEndEditing: in UISearchBarDelegate?

How to do a “show (e.g Push)” segue programatically without animation?

ios,objective-c,swift,storyboard,segue

What the show (e.g. Push) segue does internally is to call -[UIViewController showViewController:sender:] Calling this method on your view controller itself, will trigger the appropriate way of presenting the view controller you are passing. // Swift self.showViewController(viewControllerToShow, sender: self) // Objective-C [self showViewController: viewControllerToShow sender: self]; The animation can be...

Reference method from different class as curried function

swift,methods,currying

As methods in Swift are curried class functions, compiler has to decide which overload to choose. To reference instance's merge method you need to specify it's exact type: let instanceMerge: RACSignal -> RACSignal! -> RACSignal! = RACSignal.merge...

Difference between stringByAppendingString and appendString in ios

ios,objective-c,swift,nsstring,nsmutablestring

appendString: is from NSMutableString, stringByAppendingString: is from NSString. The first one mutates the existing NSMutableString. Adds to the end of the receiver the characters of a given string. The second one returns a new NSString which is a concatenation of the receiver and the parameter. Returns a new string made...

AppleScript (or swift) add hours to time

swift,date,applescript

You need to pick the hours as an individual variable, like shown below: set currentDate to current date set newHour to ((hours of currentDate) + 8) You can also use this for days, minutes and seconds. This will work. You can then use the variables to construct a new date...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController

ios,swift,uitableview,uiviewcontroller

You just need to add this to your code in viewDidLoad. self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero]; EDIT: sorry i was written in objective -c here is in swift. self.tableView.tableFooterView = UIView(frame:CGRectZero) The tableview will display what appear to be extra blank rows to fill out the bounds if there are not...

Beacon / IOS CLLocationManager get current region

ios,swift,cllocationmanager,ibeacon

You can use the locationManager:didDetermineState:forRegion: callback, which tells you if you are either Inside, Outside or Unknown. You can force yourself to get a callback by calling locationManager.requestStateForRegion(region) when your app starts up. See more here: https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManagerDelegate_Protocol/#//apple_ref/occ/intfm/CLLocationManagerDelegate/locationManager:didDetermineState:forRegion:...

How to save text field value in uicollectionviewcell

swift,uitextfield,uicollectionviewcell

Implement in your ViewController the UITextFieldDelegate protocol, specifically the textField:didEndEditing method. Save your indexPath.row in the textField.tag as you're doing, and set the delegate to the controller, where you can save the value. This is a very simplistic example: class MyViewController : UITableViewController { var texts = [Int:String]() func tableView(tableView:...

iOS 8 Swift CS193P Calculator Bug Switch Operation

ios,swift

Your code looks fine, it looks like you accidentally placed a breakpoint in your code, see that blue-looking arrow to the left of the green-highlighted line? Do one of the following: Go ahead and right click that and click Delete Breakpoint Drag and drop that breakpoint into your view controller...

Getting video from Asset Catalog using On Demand ressources

ios,xcode,xcode7,ios9,asset-catalog

I think its not possible to use Asset Catalog for video stuff, Its simplify management of images. Apple Documentation Use asset catalogs to simplify management of images that are used by your app as part of its user interface. An asset catalog can include: Image sets: Used for most types...

Read plist inside ~/Library/Preferences/

objective-c,xcode,osx

You need to use NSString method: stringByExpandingTildeInPath to expand the ~ into the full path. NSString *resPath = [@"~/Library/Preferences/" stringByExpandingTildeInPath]; NSLog(@"resPath: %@", resPath); Output: resPath: /Volumes/User/me/Library/Preferences ...

animating a view on top of uitableview

ios,swift,autolayout

In initializeSettingsView() add nibView.setTranslatesAutoresizingMaskIntoConstraints(false). And then in viewDidload add the hight constraint to settingsView constraints.append(NSLayoutConstraint(item: settingsView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 90.0)) And you do not need to set the position of settingsView, since it will be layout at the right position based on...

How to create UITableViewCells with complex content in order to keep scrolling fluent

ios,swift,uitableview,cocoa-touch,ios-charts

What you're trying to do is going to inevitably bump into some serious performance issues in one case or another. Storing all cells (and their data into memory) will quickly use up your application's available memory. On the other hand dequeueing and reloading will produce lags on some devices as...

MFMessageComposeViewControllerDelegate not being called

ios,swift

It's crashing because your handler object is getting released and deallocated right after the call to handler.sendMessage(), and then a delegate callback is attempted on that now-deallocated object when you try to send or hit cancel. The object is getting released and deallocated because nothing is holding a strong reference...

Swift timer in milliseconds

xcode,swift

As Martin says in his comment, timers have a resolution of 50-100 ms (0.02 to 0.1 seconds). Trying to run a timer with an interval shorter than that will not give reliable results. Also, timers are not realtime. They depend on the run loop they are attached to, and if...

Get NSString from NSMutableArray on Swift

swift,nsmutablearray

Try componentsJoinedByString func cualidadesToString() -> NSString{ return cualidades.componentsJoinedByString(",") } But you should use Swift's builtin String and Array types to make it more type-safe. var cualidades = [String]() func addCualidad(cualidad: String){ cualidades.append(cualidad) } func delCualidad(cualidad: String){ if let cindex = find(cualidades, cualidad) { cualidades.removeAtIndex(cindex) } } func cualidadesToString() -> String{...

Parse and Swift Geopoints not saving

swift,parse.com,geopoints

That is because you are setting it but you are not saving the value you just set: if signUpError == nil { PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if error == nil { PFUser.currentUser()!.setValue(geoPoint, forKey: "location") PFUser.currentUser().saveInBackground() } } ...

PFUser not unwrapped - swift

ios,xcode,swift

Here is explanation: What is an "unwrapped value" in Swift? PFFacebookUtils.logInWithPermissions(["public_profile", "user_about_me", "user_birthday"], block: { user, error in if user == nil { println("the user canceled fb login") //add uialert return } //new user else if user!.isNew { println("user singed up through FB") //get information from fb then save to...

Swift Range on the fly 1…12.contains(1) Cannot invoke 'contains' with (Int)

swift,range

In this case the problem was that of operator precedence: (1...12).contains(1) // -> true (the code does look ambiguous otherwise)...

Characters and Strings in Swift

ios,string,swift,unicode,character

When a type isn't specified, Swift will create a String instance out of a string literal when creating a variable or constant, no matter the length. Since Strings are so prevalent in Swift and Cocoa/Foundation methods, you should just use that unless you have a specific need for a Character—otherwise...

Transferring an Xcode project to another computer with all files/frameworks

ios,xcode,frameworks,transfer,projects

Try transferring everything from plists to the storyboard. I did this with a friend of mine and it only took about 20 minutes for the code to build and run successfully on his own laptop. the biggest issue is going to be transferring the files that Xcode is going to...