Different table view cell row heights for differen

2019-02-20 22:57发布

How can I change this UITableViewController custom class to dynamically change the height of the Table View Cells? I have specified different font sizes for the iPad and iPhone size classes. (This is a continuation of a previous discussion with @rdelmar)

#import "CREWFoodWaterList.h"

@interface CREWFoodWaterList ()

@end

@implementation CREWFoodWaterList

#define VIEW_NAME @"FoodWaterList" // add to database for this view and notes view
#define VIEW_DESCRIPTION @"Food Water - items to keep available" // to add to the database
#define RETURN_NC @"NCSuggestedContentsMenu" // where to return to when complete processing should be specified there

#define NOTES_TITLE @"Food and Water Notes" // pass to notes VC
#define THIS_NC @"NCFoodWaterList" // pass to next VC (so returns to the NC for this view)

- (IBAction)changedSwitch:(UISwitch *)sender {

if (sender.tag == 0) {
    [self saveSwitch: @"switchWater" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 1) {
    [self saveSwitch: @"switchCanned" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 2) {
    [self saveSwitch: @"switchComfort" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 3) {
    [self saveSwitch: @"switchSpecial" toValue:[NSNumber numberWithBool:sender.on]];
}
} // end of changedSwitch

-(void)loadSavedSwitches {
// now set the switches to previously stored values

NSNumber *switchValue;

switchValue = [self getSwitch: @"switchWater"];

if ([switchValue intValue] == 0) {
    self.switchWater.on = NO;
} else {
    self.switchWater.on = YES;
}
self.textWater.text = [self getDescription:@"switchWater"];

switchValue = [self getSwitch: @"switchCanned"];
if ([switchValue intValue] == 0) {
    self.switchCanned.on = NO;
} else {
    self.switchCanned.on = YES;
}
self.textCanned.text = [self getDescription:@"switchCanned"];


switchValue = [self getSwitch: @"switchComfort"];
if ([switchValue intValue] == 0) {
    self.switchComfort.on = NO;
} else {
    self.switchComfort.on = YES;
}
self.textComfort.text = [self getDescription:@"switchComfort"];
//    self.textComfort.textColor = [UIColor whiteColor];

switchValue = [self getSwitch: @"switchSpecial"];
if ([switchValue intValue] == 0) {
    self.switchSpecial.on = NO;
} else {
    self.switchSpecial.on = YES;
}
self.textSpecial.text = [self getDescription:@"switchSpecial"];

}

- (void) createNewSwitches {
//  set create all switches and set to off

[self newSwitch: @"switchWater" toValue:@"At least three litres of bottle water per person per day"];
[self newSwitch: @"switchCanned" toValue:@"Canned foods, dried goods and staples"];
[self newSwitch: @"switchComfort" toValue:@"Comfort foods"];
[self newSwitch: @"switchSpecial" toValue:@"Food for infants, seniors and special diets"];
}
// COMMON Methods

- (void)viewDidLoad {
    [super viewDidLoad];

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50;


NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

// set font size for table headers

[[UIDevice currentDevice] model];
NSString *myModel =  [[UIDevice currentDevice] model];
NSInteger nWords = 1;
NSRange wordRange = NSMakeRange(0, nWords);
NSArray *firstWord = [[myModel componentsSeparatedByString:@" "] subarrayWithRange:wordRange];
NSString *obj = [firstWord objectAtIndex:0];

if ([obj isEqualToString:@"iPad"]) {
    [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:26]];}
else if ([obj isEqualToString:@"iPhone"]) {
    [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:16]];
};

[defaults setObject:NOTES_TITLE forKey: @"VCtitle"]; // pass to notes VC
[defaults setObject:VIEW_NAME forKey: @"VCname"]; // pass to notes VC to use to store notes
[defaults setObject:THIS_NC forKey: @"CallingNC"];    // get previous CallingNC and save it for use to return to in doneAction

[self initializeView];
} // end of viewDidLoad

-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.tableView reloadData]; // this was necessary to have the cells size correctly when the table view first appeared
}

- (void) initializeView {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"View" inManagedObjectContext:context];

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(viewName = %@)", VIEW_NAME];
[request setPredicate:pred];

NSError *error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];

if ([objects count] == 0) { // create new view instance
    NSManagedObject * newView;
    newView = [NSEntityDescription insertNewObjectForEntityForName:@"View" inManagedObjectContext:context];
    [newView setValue:VIEW_NAME forKey:@"viewName"];
    [newView setValue:VIEW_DESCRIPTION forKey:@"viewDescription"];

    //  create all switches and set to off
    [self createNewSwitches];
}
//  load all switches
[self loadSavedSwitches];
} // end of initializeView

// create a new switch
- (void) newSwitch:(NSString*)switchName toValue:(NSString*)switchDescription {
NSError *error = nil;
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSManagedObject * newSwitch;

newSwitch = [NSEntityDescription insertNewObjectForEntityForName:@"Switch" inManagedObjectContext:context];
[newSwitch setValue:VIEW_NAME forKey:@"viewName"];
[newSwitch setValue:switchName forKey:@"switchName"];
[newSwitch setValue:switchDescription forKey:@"switchDescription"];
[newSwitch setValue:[NSNumber numberWithInt:0] forKey:@"switchValue"];
if (! [context save:&error])
    // NSLog(@"**** START entering %@",VIEW_NAME);
    NSLog(@"newSwitch Couldn't save new data! Error:%@", [error description]);
} // end of newSwitch

// read existing switch settings
- (NSNumber *) getSwitch:(NSString*)switchName {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Switch" inManagedObjectContext:context];

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(viewName = %@) AND (switchName = %@)", VIEW_NAME, switchName];
[request setPredicate:pred];

// Execute Fetch Request
NSManagedObjectContext * matches = nil;
NSError *fetchError = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&fetchError];
if (fetchError) {
};

NSNumber *switchValue;

if (! [objects count] == 0) {
    matches = objects [0];
    switchValue = [matches valueForKey : @"switchValue"];
}

return switchValue;
} // end of getSwitch

- (NSString *) getDescription:(NSString*)switchName {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Switch" inManagedObjectContext:context];

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(viewName = %@) AND (switchName = %@)", VIEW_NAME, switchName];
[request setPredicate:pred];

// Execute Fetch Request
NSManagedObjectContext * matches = nil;
NSError *fetchError = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&fetchError];
if (fetchError) {
    // NSLog(@"**** START entering %@",VIEW_NAME);(@"getSwitch Fetch error:%@", fetchError); // no
};

NSString *switchDescription;

if (! [objects count] == 0) {
    matches = objects [0];
    switchDescription = [matches valueForKey : @"switchDescription"];
}
return switchDescription;
} // end of getDescription


- (void)saveSwitch:(NSString*)switchName toValue:(NSNumber*)newSwitchValue {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Switch" inManagedObjectContext:context]; // get switch entity

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(viewName = %@) AND (switchName = %@)", VIEW_NAME, switchName ];
[request setPredicate:pred];

NSManagedObject *matches = nil;
NSError *fetchError = nil;
NSArray * objects = [context executeFetchRequest:request error:&fetchError];

if (![objects count] == 0) {
    matches = objects[0];
}

[matches setValue:newSwitchValue forKey:@"switchValue"];

if (! [context save:&fetchError])
    // NSLog(@"**** START entering %@",VIEW_NAME);
    NSLog(@"saveSwitch Couldn't save data! Error:%@", [fetchError description]); // perhaps this can be Done later
} // end of saveSwitch

// set alternate cells to different colors

- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];

// Create color object, specifying alpha as well
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
                green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
                 blue:((CGFloat) (hexint & 0xFF))/255
                alpha:alpha];

return color;
}
// Helper method..

- (unsigned int)intFromHexString:(NSString *)hexStr
{
unsigned int hexInt = 0;

// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];

// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];

// Scan hex value
[scanner scanHexInt:&hexInt];

return hexInt;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *grayishCyan = @"#a3c9ca";
NSString *grayishRed = @"#caa4a3";
UIColor *colorCyan = [self getUIColorObjectFromHexString:grayishCyan alpha:.9];
UIColor *colorPink = [self getUIColorObjectFromHexString:grayishRed alpha:.9];
//    // NSLog(@"**** START entering %@",VIEW_NAME);(@"UIColor: %@", colorPink);

if (indexPath.row == 0 || indexPath.row%2 == 0) {
    cell.backgroundColor = colorCyan;
}
else {
    cell.backgroundColor = colorPink;
    }
}

- (IBAction)doneAction:(id)sender {
//        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    UIViewController *viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]  instantiateViewControllerWithIdentifier:RETURN_NC];  // previous Navigation controller
[self presentViewController:viewController animated:YES completion:nil];
};


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];

}

@end

标签: xcode xcode6
0条回答
登录 后发表回答