Menu
  • HOME
  • TAGS

How to use indexesOfObjectsPassingTest: in Swift

Tag: ios,closures,swift

The declaration of indexesOfObjectsPassingTest: looks like this in Swift,

func indexesOfObjectsPassingTest(predicate: ((AnyObject!, Int, CMutablePointer<ObjCBool>) -> Bool)!) -> NSIndexSet!

I've tried all sorts of permutations to get this to work, but I'm stumped, particularly with how you deal with this piece, CMutablePointer<ObjCBool>) -> Bool)!. I found it confusing enough, when I was first learning blocks in objective-c, how you translate from the declaration to actual use of a method, and the syntax of Swift is at least as confusing.

Best How To :

This code is working in the Playground for me ;) Hope it helps a bit

Extra Function-Definition

import Cocoa

let list = [2, 3, 4, 5, 6, 7, 8]

func test (object: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool
{
    let number = object as Int
    return (number % 2 == 0) //for even numbers
}

let result: NSIndexSet = (list as NSArray).indexesOfObjectsPassingTest(test)

println("\(result.lastIndex)") //prints "6" (because 8%2=0)

Inline-Closure

I transformed my above example to work with an inline-closure (described in the Swift-eBook). The parameter-list and return-type is separated by the term in.

import Cocoa

let list = [2, 3, 4, 5, 6, 7, 8]

let result: NSIndexSet = (list as NSArray).indexesOfObjectsPassingTest({
(object: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool in
    let number = object as Int
    return (number % 2 == 0) //for even numbers
})

println("\(result.lastIndex)") //prints "6" (because 8%2=0)

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:...

NS_ENUM as property in protocol

ios,objective-c,automatic-ref-counting

You needs to synthesize the property: @implementation Application @synthesize applicationState = _ applicationState; @end or declare the property again: @interface Application : NSObject <ApplicationProtocol> @property (nonatomic) ApplicationState applicationState; @end ...

try to recover views from custom cell

ios,uitableview

viewWithTag: is a very fragile way to get a reference to views, and isn't recommended. But what I think is happening is that you need to call viewWithTag: on cell.contentView rather than the cell itself. I'd recommend creating proper IBOutlets to hold your imageview and label....

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...

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.

Call method after asynchronous request obj-c

ios,objective-c,asynchronous,uiviewcontroller,nsobject

You'll have to 'remember' which UIViewController calls the object. This can be done for instance with a property. in .h @property (nonatomic) UIViewController *viewController; in your .m file @synthesize viewController; Before calling the method, set the property with anObject.viewController = self; Then, you'll be able to call [viewController finishedPost:self]; inside...

Override UITabBarController Icon Selection

ios,objective-c,uitabbarcontroller

UITabBarControllerDelegate has a delegate method - tabBarController:shouldSelectViewController:, just implement it and check if user is logged in or not. e.g. - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController { if (isLogin) { return YES; } else{ //show your view controller here return NO; } } You can also check which view controller has...

Scaling everything up and down for different devices in UIStoryboard

ios,uistoryboard

You can do it by using Aspect Ratio property of AutoLayout. You can follow this tutorial. It gives a very nice explanation on how to scale everything up by using fix aspect ratio. http://simblestudios.com/blog/development/percentage-width-in-autolayout.html...

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 ...

Is it possible to obtain an unique iCloud user ID on cocoa?

ios,iphone,cocoa,ipad,icloud

Yes, this is possible using CloudKit. You'll need a CKContainer, and you'll ask it to fetch the user record ID. That record ID is unique for your apps, but is also stable for that user this means the same iCloud account will have the same record ID, regardless of which...

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...

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...

Slide in an UIButton and push other UIButton when a certain distance is reached

ios,objective-c,uiviewanimation,nslayoutconstraint

Since you would expect the orange button to move at some point, you can't force it to be centered. Lower the priority from 1000 to something lower. This means: I would really like it to be centered, but it doesn't have to be. Add a horizontal distance (leading/trailing) constraint...

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) ...

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); } -...

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...

UITabBarViewController doesn't rotate - iOS

ios,uitabbarcontroller,auto-rotation,shouldstartload

Try to override this method, don't call super - (void)viewWillTransitionToSizeCGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { //[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; [self.selectedViewController viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; } ...

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...

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...

Change background color of viewcontroller but not top area with clock

ios,user-interface,uiviewcontroller

The "top area with clock" is called a status bar. That bar is transparent and is displayed as the topmost view in a window. This means that nothing can cover the status bar. You can show, hide and change the appearance of the status bar (changing the content from Light...

NSString to NSDate doesn't work

ios,objective-c,nsdateformatter

You have to set the date format as the string NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"]; NSDate *date = [dateFormatter dateFromString:myDate]; //Set New Date Format as you want [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSLog(@"%@",[dateFormatter stringFromDate:date]); ...

IOS - Adjust cell height based on content

ios,uitableview,autolayout

If use AutoLayout the use this code You try to set the UITableView properties estimatedHeight. -(void)viewWillAppear:(BOOL)animated{ _messageField.delegate = self; _tableView.estimatedRowHeight = 65.0; _tableView.rowHeight = UITableViewAutomaticDimension; } Other wise use this UITableView Delegate Method - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 300; // your dynamic height... } ...

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...

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>...

Twilio Client Python not Working in IOS Browser

javascript,python,ios,flask,twilio

Twilio developer evangelist here. Twilio Client uses WebRTC and falls back to Flash in order to make web browsers into phones. Unfortunately Safari on iOS supports neither WebRTC nor Flash so Twilio Client cannot work within any browser on iOS. It is possible to build an iOS application to use...

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...

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"; ...

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...

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...

iPod Touch (5th gen) 'Source type 1 not available' crash when using UIImagePickerControllerSourceTypeCamera

ios,objective-c,ipod-touch

First, You should always validate if the resource is available or not, try using: if(IS_IPAD && imagePicker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){ if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { // present the popover } else { // HEY, YOU CAN'T USE THIS } } From the official docs: Because a media source may not be present...

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?

Trying to dismiss a popover view controller with a table view inside of it

ios,objective-c,uipopovercontroller

You have to set the delegate of your AssistanceNeededAtPopOverViewController that pops the controllerview, as the new GlobalPageSideDetailViewController. Here you're setting the delegate of a controller you just instantiate and not the one which poped the controller. ...

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...

Set color CFAttributedStringRef

ios,objective-c

Based on the comments on the question, you mentioned that the words will never change. You could potentially create a whole bunch of if/else statements checking every word selected against every word in an array. I have put this down as a more efficient alternative and it should hopefully work....

After an insert into the UITableView : custom the cell

ios,objective-c,uitableview

You need to use UITextField instead of UILabel. When you insert a new cell, set this UITextField's enabled property to true. When loading all the other cells remember to set it to false to disable editing (the same cell maybe used at more than one place)....

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...

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...

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...

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....

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() } } ...

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...

Why doesn't a UITableView scroll until I have 2 additional rows?

ios,uitableview

UIScrollView (from which UITableView inherits) has a alwaysBounceVertical property. If you set this to true, either in code or Storyboard, the table view will be vertically 'scrollable' regardless of how many rows it has.

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...

Adding Image And title both to UIsegmentControl IOS

ios,uiimage,title,uisegmentedcontrol

The official documentation for -setImage:forSegmentAtIndex: says A segment can only have an image or a title; it can’t have both. There is no default image. So, no, there is no way to do what you want using the image and title properties. However, there are a few options to accomplish...

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...

How to draw each a vertex of a mesh as a circle

ios,unity3d,shader,mesh,particle

You can do it using geometry shaders to create billboarding geometry from each vertex on the GPU. You can then either create the circles as geometry, or create quads and use a circle texture to draw them (I recommend the later). But geometry shaders are not extensively supported yet, even...

App crashes when i start typing in uiseachbar in uitableview

ios

It seems that the Predicate is incorrect Try : NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.fullName contains[c] %@", searchText]; ...

SpriteKit collision angle of line and circle is odd

ios,sprite-kit,skphysicsbody

The ball gets reflected symmetrically to its angle of approach assuming it's a completely elastic collision. That means, to get the behavior you are looking for, the ball would need to approach exactly from one line mid-point to the next without any loss of energy. Sprite Kit's physics engine will...

ios8 Timezone parsing changed?

ios,nsdateformatter

Setting dateStyle or timeStyle will override any custom dateFormat you have set. Your date string does not conform in any way to NSDateFormatterShortStyle, which is why you are getting nil when trying to convert strings to dates. Furthermore, according to Unicode Technical Standard #35 revision 31, the timezone specifier of...

iOS: Go back to entry point view controller which is not part of navigation controller

ios,uinavigationcontroller,swrevealviewcontroller

Just set window.rootViewController to the login view controller.