How can I optimize if-else statement to be more simple? - objective-c

Im working with the code below in developing simple ios app using objective-C.Is that have another way to optimize this code:
if ([segue.identifier isEqualToString:#"showCommitDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
CommitDetailsTableViewController *destViewController = segue.destinationViewController;
RepoObject *repoObj = [self.RepoListArray objectAtIndex:indexPath.row];
NSString *repoCommit_url = [repoObj.Commit_url stringByReplacingOccurrencesOfString:#"{/sha}" withString:#""];
if (indexPath.row == 0) {
NSString *SpringBootURL = repoCommit_url;
self.commit_url = SpringBootURL;
destViewController.CommitRepoURL = self.commit_url;
destViewController.navigationItem.title = #"Spring-Integration-in-Action";
}else if (indexPath.row == 1){
NSString *SpringFrameworkURL = repoCommit_url;
self.commit_url = SpringFrameworkURL;
destViewController.CommitRepoURL = self.commit_url;
destViewController.navigationItem.title = #"spring-data-jdbc-ext";
}else if (indexPath.row == 2){
NSString *SpringAmqpURL = repoCommit_url;
self.commit_url = SpringAmqpURL;
destViewController.CommitRepoURL = self.commit_url;
destViewController.navigationItem.title = #"spring-data-commons";
}else if (indexPath.row == 3){
NSString *SpringIdeURL = repoCommit_url;
self.commit_url = SpringIdeURL;
destViewController.CommitRepoURL = self.commit_url;
destViewController.navigationItem.title = #"spring-data-graph";
}else{
NSString *SpringIntegratURL = repoCommit_url;
self.commit_url = SpringIntegratURL;
destViewController.CommitRepoURL = self.commit_url;
destViewController.navigationItem.title = #"spring-data-document-examples";
}
}
Beside that, how can i assign title directly without hard-coding it like i did above.?

if ([segue.identifier isEqualToString:#"showCommitDetail"]) {
NSInteger selectedRow = [self.tableView indexPathForSelectedRow].row;
CommitDetailsTableViewController *destViewController = segue.destinationViewController;
RepoObject *repoObj = [self.RepoListArray objectAtIndex:selectedRow];
self.commit_url = [repoObj.Commit_url stringByReplacingOccurrencesOfString:#"{/sha}" withString:#""];
destViewController.CommitRepoURL = self.commit_url;
NSString *title;
switch (selectedRow) {
case 0:
title = #"Spring-Integration-in-Action";
break;
case 1:
title = #"spring-data-jdbc-ext";
break;
case 2:
title = #"spring-data-commons";
break;
case 3:
title = #"spring-data-graph";
break;
default:
title = #"spring-data-document-examples";
break;
}
destViewController.navigationItem.title = title;
}

You can try change the second if elses to the following, it will optimize lines of code and legibility.
NSString *url = repoCommit_url;
self.commit_url = url;
destViewController.CommitRepoURL = self.commit_url;
if (indexPath.row == 0) {
destViewController.navigationItem.title = #"Spring-Integration-in-Action";
}else if (indexPath.row == 1){
destViewController.navigationItem.title = #"spring-data-jdbc-ext";
}else if (indexPath.row == 2){
destViewController.navigationItem.title = #"spring-data-commons";
}else if (indexPath.row == 3){
destViewController.navigationItem.title = #"spring-data-graph";
}else{
destViewController.navigationItem.title = #"spring-data-document-examples";
}

Related

overriding cells in UITableView while scrolling

I know this is repeated question but i am not getting solution on my issue..I have designed UITableView programmatically but it's working fine till 4 sections or 9 rows but when I am trying to add any extra cell it's overriding first cell on last cell and vice versa.Please solve my issue.Thanks in advance.
my code is -
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 6;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
return 1;
else if (section == 1)
return 1;
else if (section == 2)
return 3;
else if (section == 3)
return 2;
else if (section == 4)
return 2;
else if (section == 5)
return 3;
else
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
if ((indexPath.section == 0) && (indexPath.row ==0)) {
cell.textLabel.text = #"";
//Get it from previous view
chooseEventLbl.text = #"Choose an event";
//chooseEventLbl.textColor = [UIColor darkGrayColor];
[cell addSubview:chooseEventLbl];
//cell.textLabel.text = #"Choose an event";
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
[image setImage:[UIImage imageNamed:#"arrow_list.png"]];
cell.accessoryView = [[UIImageView alloc]initWithFrame:CGRectMake(260.0, 7.0, 10, 20)];
[cell.accessoryView addSubview:image];
}
else if ((indexPath.section == 1) && (indexPath.row == 0))
{
cell.textLabel.text = #"";
[cell addSubview:squareNameTxt];
}
else if ((indexPath.section == 2) && (indexPath.row == 0))
{
cell.textLabel.text = #"Public";
}
else if ((indexPath.section == 2) && (indexPath.row == 1))
{
cell.textLabel.text = #"Private";
}
else if ((indexPath.row == 2) && (indexPath.row == 2) && (passwordFlag == TRUE))
{
cell.textLabel.text = #"";
[cell addSubview:passwordTxt];
// passwordTxt.enabled = NO;
}
else if ((indexPath.section == 3) && (indexPath.row == 0))
{
cell.textLabel.text = #"Allow multiple Squares";
[aSwitch addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
aSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:aSwitch];
}
else if ((indexPath.section == 3) && (indexPath.row == 1)) {
cell.textLabel.text = #"";
[cell addSubview:multiSquareListBtn];
}
else if ((indexPath.section == 4) && (indexPath.row == 0))
{
cell.textLabel.text = #"Prizes";
}
else if ((indexPath.section == 4) && (indexPath.row == 1))
{
cell.textLabel.text = #"";
[cell addSubview: firstQuarterTxt];
[cell addSubview:halftimeTxt];
[cell addSubview:thirdQuarterTxt];
[cell addSubview:finalTxt];
}
else if ((indexPath.section == 5) && (indexPath.row ==0))
{
cell.textLabel.text= #"";
currentLocationLbl.text = #"Choose Current Location";
[cell addSubview:currentLocationLbl];
}
else if ((indexPath.section == 5) && (indexPath.row == 1))
{
cell.textLabel.text = #"";
mapLocationLbl.text = #"Choose location from Map";
[cell addSubview:mapLocationLbl];
}
else if ((indexPath.section == 5) && (indexPath.row == 2))
{
cell.textLabel.text = #"";
radiusLocationLbl.text = #"Location Radius";
[cell addSubview:radiusLocationLbl];
}
return cell;
}

Reducing the length of a long for/if statement

I'm currently trying to make the code of an app I'm developing a bit more efficient and easier to read. Basically what this does is retrieve an array from NSUserDefaults of player names, and fills in the 6 text boxes (tagged 6-11) with these names. If there isn't an existing array it'll use another set of names. Any ideas for simplifying this code would be appreciated.
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
NSMutableArray *names = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"nameArray"]];
for (int i = 0; i <= 5; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UITableViewCell *cell = [playerTable cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *txtField = (UITextField *)view;
if (txtField.tag == 6) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:0]; }
else {
txtField.text = #"Peter";
}
}
if (txtField.tag == 7) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:1]; }
else {
txtField.text = #"Julia";
}
}
if (txtField.tag == 8) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:2]; }
else {
txtField.text = #"Durgan";
}
}
if (txtField.tag == 9) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:3]; }
else {
txtField.text = #"Bob";
}
}
if (txtField.tag == 10) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:4]; }
else {
txtField.text = #"Iseland";
}
}
if (txtField.tag == 11) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:5]; }
else {
txtField.text = #"Player";
}
}
}
}
}
[self saveNames];
}
Your could do this:
NSArray *defaultNames = #[#"Peter", #"Julia",...];
int offsetIndex = 6;
BOOl needCustomNames = [[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"];
for (UIView *view in cell.contentView.subviews)
{
if ([view isKindOfClass:[UITextField class]])
{
UITextField *txtField = (UITextField *)view;
int index = [txtField tag]-offsetIndex;
if (tag >= 6 && tag <= 11)
{
if (needCustomNames)
textField.text = [names objectAtIndex:index];
else
textField.text = [defaultNames objectAtIndex:index];
}
}
}
For example, you called too many times the same lines in the for loop, like checking if you need to use or not a custom names (NSUserDefaults line).
I use an NSArray for the custom names to mimic the same logic, and used an offset to clarify it.
I would recommend to analyse your Code for redundance and exclude them in separate methods. so you have to call only the extern method than every code-party again and again.

UITableView values don't match its key form plist

I am making a plist viewer and editor for iOS, but the problem I have it, that the values don't match to its key. Like I have this plist
{
BuildMachineOSBuild = 12C54;
CAProcessCanAccessGPU = 1;
CFBundleAllowMixedLocalizations = 1;
CFBundleDevelopmentRegion = English;
CFBundleDisplayName = iAd;
CFBundleExecutable = AdSheet;
CFBundleIconFiles = (
"iAd.png",
"iAd#2x.png"
);
CFBundleIcons = {
CFBundlePrimaryIcon = {
CFBundleIconFiles = (
"iAd.png",
"iAd#2x.png"
);
UIPrerenderedIcon = 0;
};
};
CFBundleIdentifier = "com.apple.AdSheetPhone";
CFBundleInfoDictionaryVersion = "6.0";
CFBundleName = AdSheet;
CFBundlePackageType = APPL;
CFBundleResourceSpecification = "ResourceRules.plist";
CFBundleShortVersionString = "1.0";
CFBundleSignature = "????";
CFBundleSupportedPlatforms = (
iPhoneOS
);
CFBundleVersion = "1.0";
CLSystemService = 1;
CLVisibleImmediately = 1;
CanInheritApplicationStateFromOtherProcesses = 1;
DTCompiler = "com.apple.compilers.llvm.clang.1_0";
DTPlatformBuild = "";
DTPlatformName = iphoneos;
DTPlatformVersion = "7.0";
DTSDKBuild = 11A450;
DTSDKName = "iphoneos7.0.internal";
DTXcode = 0500;
DTXcodeBuild = 5A1344i;
MinimumOSVersion = "7.0";
NSPrincipalClass = ADSApplication;
SBAppTags = (
hidden
);
SBMachServices = (
"com.apple.AdSheetPhone.server",
"com.apple.AdSheetPhone.management",
"com.apple.uikit.viewservice.com.apple.AdSheetPhone"
);
UIBackgroundModes = (
continuous
);
UIDeviceFamily = (
1,
2
);
UIShouldIgnoreRemoteControlEvents = 1;
UIStatusBarHidden = 1;
UISupportedInterfaceOrientations = (
UIInterfaceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight
);
UIViewServiceUsesNSXPCConnection = 1;
}
)
I try to display the value and its key (or Dictionary for Dictionaries, Array for Arrays and Bool for Bools)
Then for example CanInheritApplicationStateFromOtherProcesses should show a 1 (wich is a BOOL), but is don't show any value. And CanInheritApplicationStateFromOtherProcesses is on index 0 of my UITableView, but it is on index 19 of the plist. Does anyone know how to fix this error. I am displaying the key in the cell.textLabel.text and the value in cell.detailTextLabel.text. Here is my code of - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"plist Cell" forIndexPath:indexPath];
id obj;
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.detailTextLabel.minimumScaleFactor = 0.5;
cell.textLabel.font = [UIFont systemFontOfSize:14];
cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
cell.editingAccessoryType = UITableViewCellEditingStyleNone;
if (self.plistDict) {
NSString* key = [[self.plistDict allKeys] objectAtIndex:indexPath.row];
cell.textLabel.text = key;
obj = [self.plistDict objectForKey:key];
} else {
cell.textLabel.text = [NSString stringWithFormat:#"%li", (long)indexPath.row];
obj = [self.plistArray objectAtIndex:indexPath.row];
}
if(([obj isKindOfClass:[NSArray class]] || [obj isKindOfClass:[NSMutableArray class]]) && cell.tag == 0){
cell.detailTextLabel.text = NSLocalizedString(#"Array", nil);
cell.tag = 1;
return cell;
} if(([obj isKindOfClass:[NSDictionary class]] || [obj isKindOfClass:[NSMutableDictionary class]]) && cell.tag == 0){
cell.detailTextLabel.text = NSLocalizedString(#"Dictionary", nil);
cell.tag = 2;
return cell;
} if ([obj isKindOfClass:[NSString class]] && cell.tag == 0) {
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", (NSString *)obj];
cell.tag = 3;
return cell;
} if ([obj isKindOfClass:[NSNumber class]]) {
if ([obj isKindOfClass:[#(YES) class]] && cell.tag == 0) {
[boolSwitch setOn:(BOOL)obj animated:YES];
[cell.contentView addSubview:boolSwitch];
cell.detailTextLabel.textColor = [UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.tag = 7;
return cell;
} else if (![obj isKindOfClass:[#(YES) class]] && cell.tag == 0) {
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", (NSNumber *)obj];
cell.tag = 4;
return cell;
} else {
return cell;
}
} if ([obj isKindOfClass:[NSData class]] && cell.tag == 0) {
cell.detailTextLabel.text = NSLocalizedString(#"Data", nil);
cell.tag = 5;
return cell;
} if ([obj isKindOfClass:[NSDate class]] && cell.tag == 0) {
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", (NSDate *)obj];
cell.tag = 6;
return cell;
} else {
return cell;
}
The odd thing is for the most keys the value matches, but not for all.
cell will be reused with tag. so you maybe should reset the tag before reuse the cell:
//CustomeCell.m
- (void)prepareForReuse{
[super prepareForReuse];
self.tag = 0;
}
Or in tableView delegate class:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
cell.tag = 0;
}

Iphone uitextfield auto format like contacts app tag issue

I have a form screen on my iphone and I am trying to replicate the Iphone Contacts app where it will auto complete the following format for the phone number:
(233)323-2323.
I am very close I am able to see the format update in the textfield but the 4 other text fields are not working now. I am unable to edit them. I narrowed it down to the shouldchangecharactersinrange function.
Please see code below.
Thanks.
quick look at the method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
Firstcontroller.h
#interface FirstTVContoller : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIPickerViewDataSource,UIPickerViewDelegate>{
NSMutableArray *items;
NSMutableArray *titles;
NSMutableArray *section2items;
NSMutableArray *dataArray;
UITableView *table;
contactTitle *title;
//launch title picker
UIPickerView *titlePicker;
UILabel *titleLabel;
UITextField *titleField;
UIActionSheet *actionSheet;
UIPickerView *pickerView;
UITextField *textField;
UITextField *FirstnameTextfield;
UITextField *LastnameTextfield;
UITextField *CompanyTextfield;
UITextField *phoneTextfield;
//the scrollview
UIScrollView *scrollview;
}
//attributes for title picker
#property (strong, nonatomic) NSArray * titlecategories;
#property (strong, nonatomic) NSArray * titleidSlot;
#end
FirstTVController.m
//
// FirstTVContoller.m
// TwoTableViews
#implementation FirstTVContoller
#synthesize titleidSlot;
#synthesize titlecategories;
- (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
//NSLog(#"Error. Could not recover network reachability flags");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
NSURL *testURL = [NSURL URLWithString:SERVERNAME];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}
-(void)viewDidLoad{
[super viewDidLoad];
// scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
// scrollview.pagingEnabled = YES;
//
// //[scrollview addSubview:self.view];
// [self.view addSubview:scrollview];
table.scrollEnabled = YES;
dataArray = [[NSMutableArray alloc] init];
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 290, 30)];
//dropper
titleField = [[UITextField alloc] initWithFrame:CGRectMake(10, 2, 300, 30)];
titleField.layer.cornerRadius = 8;
titleField.backgroundColor = [UIColor clearColor];
NSArray *firstItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2", nil];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:firstItemsArray forKey:#"data"];
[dataArray addObject:firstItemsArrayDict];
//Second section dat
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:#"1", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:#"data"];
[dataArray addObject:secondItemsArrayDict];
NSArray *thirdItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
NSDictionary *thirdItemsArrayDict = [NSDictionary dictionaryWithObject:thirdItemsArray forKey:#"data"];
[dataArray addObject:thirdItemsArrayDict];
NSLog(#"the dataArray%#",dataArray);
if([self connectedToNetwork]){
dispatch_async(kBgQueue, ^{
//build the url of strings
FULLURL = [SERVERNAME stringByAppendingFormat:ushTitleLink];
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
//NSLog(#"here title url%#",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
NSLog(#"here%#",data);
//get the data from the url
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
NSLog(#"titleid:%#",TITLEID);
NSLog(#"title categories:%#",titlecategories);
});
[table setBounces:NO];
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Please Check your internet connection"
message:#"Enable your internet connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
});
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [dataArray count];
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
//Number of rows it should expect should be based on the section
NSDictionary *dictionary = [dataArray objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"data"];
return [array count];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 1){
cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"longdropper300.png"]];
}
else{
cell.backgroundColor = [UIColor whiteColor];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 10, 290, 30)];
static NSString *cellValue = #"Cell";
UITableViewCell *cell =nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellValue];
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
if ([indexPath section] == 0) {
//cellValue=[items objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle= UITableViewCellSelectionStyleNone;
//textField.tag = 1;
textField.adjustsFontSizeToFitWidth = YES;
textField.textColor = [UIColor blackColor];
if(indexPath.section == 0){
//textfield for email
if ([indexPath row] == 0) {
textField.tag = 1;
textField.text = EMAIL;
textField.textColor= [UIColor blackColor];
textField.placeholder = #"Email: example#gmail.com";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
//textfield for phone number
else {
textField.tag = 2;
if ([PHONENUMBER isEqual: [NSNull null]] && PHONENUMBER == nil && PHONENUMBER == NULL && [PHONENUMBER isEqual: #""]){
NSLog(#"phone is empty%#",PHONENUMBER);
//[PHONENUMBER isEqual:#"frank"];
}else{
NSLog(#"phone is not empty%#",PHONENUMBER);
textField.text = PHONENUMBER;
}
textField.placeholder = #"Phone: (xxx)xxx-xxxx";
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDefault;
textField.secureTextEntry = NO;
}
textField.backgroundColor = [UIColor whiteColor];
//textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
//textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
//textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
}
if(indexPath.section == 1){
[titleField setTextColor:[UIColor whiteColor]];
titleField.tag = 3;
titleField.placeholder = #"Select Contact Title";
titleField.returnKeyType = UIReturnKeyNext;
//titleField == textField.tag = 3;
if ([TITLENAME isEqual: [NSNull null]]){
NSLog(#"titlename is empty%#",TITLENAME);
}else{
NSLog(#"titlename is not empty%#",TITLENAME);
titleField.text = TITLENAME;
}
titleField.keyboardType = UIKeyboardTypeDefault;
titleField.returnKeyType = UIReturnKeyDone;
titleField.secureTextEntry = NO;
titleField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
titleField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
titleField.textAlignment = UITextAlignmentCenter;
titleField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[titleField setEnabled: NO];
titleField.delegate = self;
[cell addSubview:titleField];
NSLog(#"here is the titlename%#",TITLENAME);
}
if(indexPath.section == 2){
if ([indexPath row] == 0) {
textField.tag = 4;
textField.placeholder = #"First Name";
cell.selectionStyle= UITableViewCellSelectionStyleNone;
if ([FIRSTNAME isEqual: [NSNull null]]){
NSLog(#"firstname is empty%#",FIRSTNAME);
textField.text = #"";
}else{
textField.text = FIRSTNAME;
}
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
if([indexPath row] == 1){
textField.tag = 5;
textField.placeholder = #"Last Name";
if ([LASTNAME isEqual: [NSNull null]]){
NSLog(#"lastname is empty%#",LASTNAME);
textField.text = #"";
}else{
textField.text = LASTNAME;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyNext;
//textField.secureTextEntry = NO;
}
if([indexPath row] == 2){
textField.tag = 6;
textField.placeholder = #"Company";
if ([COMPANY isEqual: [NSNull null]]){
NSLog(#"company is empty%#",COMPANY);
textField.text = #"";
}
else{
textField.text = COMPANY;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
//]textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
return cell;
}
//Change the Height of title cell drop down
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if (indexPath.section == 1) {
if (indexPath.row == 0) {
return 30;
}
}
return 45;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if(([textField tag] == 1)){
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:textField.text] == YES)
{
EMAIL = [textField.text copy];
NSLog(#"here is the email%#",EMAIL);
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Bad Email"
message: #"Please Re-enter the email address with a valid email"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
NSLog(#"email not in proper format");
}
}
if(([textField tag] == 2)){
//NSString *phoneRegex = #"[235689][0-9]{6}([0-9]{3})?";
//NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
//valid email address
//if ([phoneTest evaluateWithObject:textField.text] == YES)
// {
//if(PHONENUMBER != nil){
NSString *tempString = [textField.text copy];
NSString *unformatted = tempString;
NSLog(#"unformatted phonenumber%#",unformatted);
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
[unformatted substringWithRange:NSMakeRange(3, 3)],
[unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"(%#)%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
NSLog(#"Formatted Phone Number: %#", formattedString);
PHONENUMBER = formattedString;
NSLog(#"here is the phone number %#",PHONENUMBER);
// }
// else
// {
// NSLog(#"Phone Number Invalid");
// UIAlertView *alert = [[UIAlertView alloc]
// initWithTitle: #"xxx-xxx-xxxx"
// message: #"Please enter a valid phone number"
// delegate: nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
// textField.text = nil;
// }
}
if(([textField tag] == 4)){
FIRSTNAME = [textField.text copy];
NSLog(#"here is the firstName%#",FIRSTNAME);
}
if(([textField tag] == 5)){
LASTNAME = [textField.text copy];
NSLog(#"here is the Last Name%#",LASTNAME);
}
if(([textField tag] == 6)){
COMPANY = [textField.text copy];
NSLog(#"here is the Company%#",COMPANY);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
title = [[contactTitle alloc] initWithDictionary:json];
//NSLog(#"here is the dictionary from json: %#", json);
NSLog(#"here is title that was the json %#", title);
NSLog(#"here is the title from json: %#", title.cTitle);
NSLog(#"here is the title id from json %#", title.cTitleID);
}
//PickerViewController.m
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
dispatch_queue_t downloadQueue = dispatch_queue_create("data loader", NULL);
dispatch_async(downloadQueue, ^{
TITLENAME = [title.cTitle objectAtIndex:row], row;
//NSLog(#"here is the selected title%#", TITLENAME);
TITLEID = [title.cTitleID objectAtIndex:row], row;
//NSLog(#"here is the selected title%#", TITLEID);
});
//thePickerView.hidden = YES;
}
//PickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [title.cTitle count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [title.cTitle
objectAtIndex:row];
}
- (void)fetchedContactIDData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(#"here is the login info from json: %#", json);
// NSString *FALSELOGIN;
CONTACTID = [json valueForKey:#"contactid"];
NSLog(#"CONTACT ID: %#", CONTACTID);
// LOGINID = [json valueForKey:#"login"];
// NSLog(#"LOGIN ID: %#", LOGINID);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//get the country selected
//NSString *selectedCell = nil;
if(indexPath.section == 1){
titleField.text = #"Select Contact Title";
NSLog(#"you selected:%#",TITLENAME);
actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:#"Cancel"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:#selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
//[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet showInView:self.view];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}else{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
- (void)dismissActionSheet:(id)sender{
[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
//pickerButton.titleLabel.text = TITLENAME;
//titleLabel.text= TITLENAME;
titleField.text = TITLENAME;
[titleLabel reloadInputViews];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[titlePicker removeConstraints:titlePicker];
[titlePicker removeFromSuperview];
}
#end
after reviewing your code i found one thing see below here is the problem
if(([textField tag] == 2)){
//something
return YES;
}
else if([textField tag] != 1){
return NO;
}
in else if block you keep return NO it means it doesn't take any input text , change that one to return YES it'l work.

Detailtext is only showing in first tab

Got the code but detailText is only showing in the first 'column' in case 0
code is under: cellForRowAtIndexPath
if (indexPath.row == 0) {
cell.detailTextLabel.text = #"A";
}
}
else if (indexPath.row == 1){
cell.detailTextLabel.text = #"B";
}
else if (indexPath.row == 2){
cell.detailTextLabel.text = #"C";
}
else if (indexPath.row == 3){
cell.detailTextLabel.text = #"D";
}
There is an obvious right-brace mismatch, change your code to:
if (indexPath.row == 0) {
cell.detailTextLabel.text = #"A";
}
else if (indexPath.row == 1) {
cell.detailTextLabel.text = #"B";
...
You can shorten that to
cell.detailTextLabel.text = [#"ABCD" substringWithRange:NSMakeRange(indexPath.row,1)];