iOS: ActionSheetStringPicker successAction: wrong selection - ios

I am using the ActionSheetStringPicker from the ActionSheetPickers3.0 (since I no longer can use the old picker views because of iOS 8). This is how I am calling the method:
ActionSheetStringPicker *genderPicker = [[ActionSheetStringPicker alloc]
initWithTitle:#"Gender" rows:categoryTypes initialSelection:nil target:self
successAction:#selector(selectedGender:) cancelAction:#selector(cancelledGender)
origin:gender];
[genderPicker showActionSheetPicker];
My success action code is this:
-(void) selectedGender:(NSNumber *)genderSelected {
NSLog(#"selected gender: %#",genderSelected);
if (genderSelected == 0) {
NSLog(#"male");
gender.text = #"Male";
} else {
NSLog(#"female");
gender.text = #"Female";
}
}
I am getting either a 1 or 0 value from the selected gender (male/female) when I NSLog the genderSelected value. My problem is that in my if-statement it always says I picked female. I'm getting the correct value that I select from the picker, but can't seem to figure out what the problem is. Does anyone know how I can get my if-statement working? Thanks!

In your success callback method the parameter you are getting is of type NSNumber. You cannot directly compare the object of type NSNumber with int value 0. Therefore use the following :
if (genderSelected.intValue == 0) {
NSLog(#"male");
gender.text = #"Male";
} else {
NSLog(#"female");
gender.text = #"Female";
}

Well this isn't exactly what I was looking for, but it worked. I set the NSNumber that I was getting as an NSString then compared to a "0" and "1" string. Here is my solution:
-(void) selectedGender:(NSNumber *)genderSelected {
NSString *string = [NSString stringWithFormat:#"%#",genderSelected];
if ([string isEqualToString:#"0"]) {
NSLog(#"male");
} else if ([string isEqualToString:#"1"]) {
NSLog(#"female");
}
}

Related

Prevent Users from Entering Multiple Decimals In Objective-C

I am making an only number input app (still) in which users press a button, I store a value into a string to display in a label.
Works great for the most part, except I cannot figure out how to prevent users from entering more than one decimal in a single string. .
I looked at this Stack overflow question, but trying to amend the code for my own just resulted in a whole bunch of errors. Does anyone have any advice?
- (void)numberBtn:(UIButton *)sender {
if (self.sales.text.length < 10) {
if(self.sales.text.length != 0){
NSString *lastChar = [self.sales.text substringFromIndex:[self.sales.text length] - 1];
if([lastChar isEqualToString:#"."] && [sender.titleLabel.text isEqualToString:#"."] && [sender.titleLabel.text stringByAppendingString:#"."]){
return;
}
if ([lastChar isEqualToString:#""] && [sender.titleLabel.text isEqualToString:#""]){
self.numbers = #"0.";
}
if ([self.sales.text rangeOfString:#"."].length > 0) {
NSArray *array = [self.sales.text componentsSeparatedByString:#"."];
if (array.count == 2) {
NSString *decimal = array.lastObject;
if (decimal.length > 2) {
return;
}
}
}
}
self.numbers = [NSString stringWithFormat:#"%#%#",self.numbers,sender.titleLabel.text];
self.sales.text = self.numbers;
}
}
Two steps...
Check to see if the button is a decimal .
if yes, see if the current label text already contains a .
If it does, return. If not, continue processing your button input:
- (void)numberBtn:(UIButton *)sender {
NSString *btnTitle = sender.currentTitle;
NSString *curText = self.sales.text;
if ([btnTitle isEqualToString:#"."]) {
if ([curText containsString:#"."]) {
NSLog(#"%# : Already has a decimal point!", curText);
return;
}
}
// whatever else you want to do with the input...
}

How can I add search option on UIPickerview in ios?

I am using UIActionsheet uipickerview in my project. Here, I am passing value according to his id.
I mean, in uipickerview list it will show name, and after passing it takes its id.
So, for 5-10 values it is ok, but suppose I have more than 100 values with its id, then it takes to much time to scroll, find and select a value.
So, I want to add search option in it. So after clicking my Text Field that picker or pop up will come. And it shows some list first, as well as search option available there so user can type any one or two words, so according its words data will come according to word (auto search complete).
How can I implement it.
If Anyone wants it in swift...
Create a textField with name txtSearch and then in ViewDidload add below two lines
self.txtSearch.delegate=self
self.txtSearch.addTarget(self, action: #selector(self.textFieldValueChanged(TextField:)), for: UIControlEvents.editingChanged)
func textFieldValueChanged(TextField:UITextField)
{
if((TextField.text?.characters.count)!>0)
{
self.filteredArray = (self.searchInArray(srchArray: self.ArraywithFullData, withKey: "key value", Characters: TextField.text!))!
}
else
{
self.filteredArray = self.ArraywithFullData.mutableCopy() as! NSMutableArray
}
self.pickerView.reloadData()
}
func searchInArray(srchArray:NSMutableArray, withKey:String,Characters:String)->NSMutableArray
{
let resultArray=NSMutableArray()
for index in 0..<srchArray.count
{
let Dict = srchArray[index] as! [String:Any]
if let stringmatcher = Dict[withKey] as? String
{
if(stringmatcher.contains(find: Characters))
{
resultArray.add(Dict)
}
else
{
}
}
}
return resultArray
}
extension String {
func contains(find: String) -> Bool{
return self.range(of: find) != nil
}
And For Objective-C You have to Do something Like below. But don't forget to call textField Delegates.
NSMutableArray *filteredArray;
NSMutableArray *ArraywithFullData;
self.txtSearch.delegate=self
[self.txtSearch addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//
-(void)textFieldValueChanged:(UITextField *)TextField
{
if((TextField.text.length)>0)
{
filteredArray = [self searchInArray:ArraywithFullData withKey:#"key value" andCharacters:TextField.text];
}
else
{
filteredArray = [ArraywithFullData mutableCopy];
}
[self.pickerView reloadData];
}
-(NSMutableArray *)searchInArray:(NSMutableArray*)srchArray withKey:(NSString *)key andCharacters:(NSString *)charecters
{
NSMutableArray *resultArray= [[NSMutableArray alloc]init];
for (int index=0 ; index<srchArray.count; index++)
{
NSMutableDictionary *Dict = srchArray[index];
if ([Dict valueForKey:key] != nil)
{
NSString * stringmatcher = [Dict valueForKey:key];
if ([stringmatcher containsString:charecters])
{
[resultArray addObject:Dict];
}
else
{
}
}
}
return resultArray;
}
Note if data is not in form of array of Dictionaries you can remove code work that is about dictionaries

Check if string is already exist and add a number as suffix to the string in the array?

I have a name as "Ryan" and next time entering "Ryan" it should check it has the value,So it should make it "Ryan_1". The same way it should check if anytime someone added again "Ryan" it should change it to "Ryan_2".
Example:
nameArray = ["Ryan","John","Ryan_2","Rhonda","Ryan_3","Kylie","Ryan_4","John_2"];
I am using below code which is working fine while adding the name first time.
But when I am coming back to the section and editing value Ex: I changed Ryan_2 to "xyz" and again thought of keeping "Ryan" the saved value is becoming "Ryan_4" where as it supposed to be "Ryan_2" in the array. And let say if I am changing "Ryan_4" to "somenewName" now the numbering of other duplicate names also get rearranged.
NSMutableArray *array = [[NSMutableArray alloc]init];
int occurrences = 0;
for(NSString *string in nameArray) {
if ([value isKindOfClass:[NSString class]]) {
if ([string containsString:value]) {
[array addObject:string];
}
occurrences+= ([string containsString:value] ? 1 : 0);
}
}
if ([value isKindOfClass:[NSString class]]) {
if (![value isEqualToString:#""]) {
if (occurrences > 1) {
value = [value stringByAppendingFormat:#"_%d", occurrences];
}
}
}
I would recommend an extension like this:
extension NSMutableArray {
public func appendWithSuffix(strNewEntry:String) {
var n = 1
var new = strNewEntry
if self.containsObject(strNewEntry) {
new = strNewEntry + "_\(n)"
while self.containsObject( new ){
n += 1
new = strNewEntry + "_\(n)"
}
}
self.addObject( new )
}}
It will look for an exact match and insert if none is found, i.e it will add "Ryan_5" instead of "Ryan", "John_3" instead of "John" and so on.
Another approach may be to iterate thru all entries for comparison or filter the array with "namexy".hasPrefix("Ryan") to get max index of name to be inserted.
- (IBAction)SaveText:(id)sender
{
if (array.count==0)
{
[array addObject:_txtAddText.text];
}else
{
for(NSString *string in array)
{
if ([string containsString:_txtAddText.text] )
{
count = count+1;
NSString *Localstring =[NSString stringWithFormat:#"%#%d",[string stringByAppendingString:#"_"],count];
NSLog(#"%#",Localstring);
[array addObject:Localstring];
break;
}else
{
[array addObject:_txtAddText.text];
}
}
}
NSLog(#"%#",array);
}

Check if contain Null

When I print the following I get (null)
NSLog(#"%#", [[responseObject objectAtIndex:i] objectForKey:#"child"]);
Now I want to do a validation to check if it returns (null). How am I supposed to do this?
I tried the following but it doesn't work:
1.
if (![[[responseObject objectAtIndex:i] objectForKey:#"child"] isEqualToString:#"(null)"]) {
}
2.
if (![[[responseObject objectAtIndex:i] objectForKey:#"child"] isEqual:#"(null)"]) {
}
"null" isn't just a NSString. You should do some research into the concept of a null object.
What you're looking for can be written like this:
if (![[responseObject objectAtIndex:i] objectForKey:#"child"]) {
//key "child" not in dictionary
}
(null) is the representation of nil displayed by NSLog.
You can write the following:
if ([[responseObject objectAtIndex:i] objectForKey:#"child"] == nil) {
}
Or a shorter alternative:
if (![[responseObject objectAtIndex:i] objectForKey:#"child"]) {
}
Another way to check is to use string length. I know other answers are just as good, I am just giving OP and anyone else in future some more options.
NSString *childStr = [[responseObject objectAtIndex:i]objectForKey:#"child"];
if ([childStr length] < 1)
{
//no value specified - childStr is NULL
}
else
{
//there is something in the childStr - throw a party!
}
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"hello"]) {
NSLog(#"only if not null show %#",[defaults objectForKey:#"hello"]);
}
This is a way to check it from User Defaults. It will only print if the saved object does not equal null.

Detect button text in Xcode? [duplicate]

I'm just learning how to code so thanks for your patience on this simple question.
Here's my code:
- (IBAction)buttonWasPressed:(id)sender {
NSString *buttonName = [sender titleForState:UIControlStateNormal];
if (buttonName == #"Button 1") {
do something
}
How do I compare the title of the button passed as sender to a string?
Much thanks for the help.
in objective-c you can't compare strings using "==",
instead you should use the method isEqualToString from the NSString class to compare a string with another.
if ([buttonName isEqualToString: #"Button 1"]) {
// do something
}
Use -isEqualToString method:
if ([buttonName isEqualToString:#"Button 1"])
...
using == you compare ponters, not the actual string values they contain
The better way to compare string is:
NSString *string1 = <your string>;
NSString *string2 = <your string>;
if ([string1 caseInsensitiveCompare:string2] == NSOrderedSame) {
//strings are same
} else {
//strings are not same
}
I've found that with Xcode 8.3.1, it is necessary to do:
if([self.myButton isEqual: #"My text"]) {
//do this
}

Resources