1.讓tableView分組顯示 並設置navgationbar的title
-(tableview *)init
{
if(self = [super initWithStyle:UITableViewStyleGrouped])
{
self.title = @"ColorTransitation";
}
return self ;
}
2.tableView 所需的數據
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [sectionArray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[sectionArray objectAtIndex:section] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ColorTranslation"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:@"ColorTranslation"];
}
NSInteger row = [indexPath row];
NSInteger section = [indexPath section];
NSArray *arrays = [[[sectionArray objectAtIndex:section] objectAtIndex:row]
componentsSeparatedByString:@"#"];
cell.text = [arrays objectAtIndex:0];
cell.textColor = [self getColor:[arrays objectAtIndex:1]];
return cell ;
}
3。定義 得到顏色的函數
-(UIColor *)getColor:(NSString *)hexColor
{
unsigned int red,green,blue;
NSRange range ;
range.length = 2 ;
range.location = 0 ;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];
range.location = 2 ;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];
range.location = 4 ;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];
return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green/255.0f)
blue:(float)(blue/255.0f) alpha:1.0f];
}
4. tableView 的委託方法
-(void)deselect
{
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSInteger section = [indexPath section];
NSArray *arrays = [[[sectionArray objectAtIndex:section]objectAtIndex:row]
componentsSeparatedByString:@"#"];
self.navigationController.navigationBar.tintColor = [self getColor:[arrays objectAtIndex:1]];
[self performSelector:@selector(deselect) withObject:NULL afterDelay:0.5];
}
5.顯示 tableView
-(void)createSectionList:(id)wordArray
{
sectionArray = [[[NSMutableArray alloc]init]retain];
for(int i=0;i<26;i++) [sectionArray addObject:[[[NSMutableArray alloc]init]retain]];
for(NSString *word in wordArray)
{
if([word length]==0) continue ;
NSRange range = [ALPHA rangeOfString:[[word substringToIndex:1]uppercaseString]];
[[sectionArray objectAtIndex:range.location] addObject:word];
}
}
-(void)loadView
{
[super loadView];
NSString *pathname = [[NSBundle mainBundle] pathForResource:@"crayons" ofType:@"txt" inDirectory:@"/"];
NSString *wordstring = [NSString stringWithContentsOfFile:pathname];
NSArray *wordArray = [[wordstring componentsSeparatedByString:@"\n"]retain];
[self createSectionList:wordArray];
}