2011-10-24 106 views
0

我需要通过单击按钮来更改UITableViewCell中包含的UILabel的文本颜色。我创建了一个UIColor object,它在按钮单击时设置为指定颜色,并调用UITableView reloadData方法,即使颜色不变。我应该如何实现这一点?更改UITableViewCell中UILabel的文本颜色

+0

你能解释一点吗?你想改变所有行的颜色吗?还是单排? – Ilanchezhian

+0

我在UITableView的cellForRowAtIndexPath数据源方法中创建了一个自定义UILabel,当我调用UITableView reloaddata方法时,它将作为子视图添加到单元格contentView。在我的代码中,我需要根据颜色的选择更改添加到单元格中的文本的UILabel/textcolor文本的颜色。 – user574089

+0

好。假设按钮是UIBarButton,它被添加到导航栏中,我想知道是否需要更改所有标签或单个标签的颜色? – Ilanchezhian

回答

0

我假设你想改变你表格中所有行的颜色。 (如果你只是想改变一行,你将需要它的indexPath)。

创建一个跟踪颜色状态的变量BOOL。在按钮点击例程中,适当设置此值并执行[tableView reloadData]

cellForRowAtIndexPath您需要检查变量并设置颜色为每个状态。您必须双向执行此操作,否则在滚动时单元格的状态将变得不可预知。

+0

thnx回答 – user574089

0

对于改变一个UITableViewCell的文本颜色,你必须实现UITableViewDataSource委托功能

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath(NSINdexPath*)indexPath

在那里,你得到的细胞与

 

UITableViewCell *tableViewcell = [self.tableView dequeueReusableCellWithIdentifier: @"Cell"]; 

if (tableViewCell == nil) 
{ 
    tableViewCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"] autorelease]; 
} 

在这里你可以改变文字的颜色。

BTW:你应该接受一些答案您得到您的问题 - 这将提高你的机会,以获得未来的问题的答案......

0

精细,当你添加自定义的UILabel的内容查看,设置标签为UILabel。

UILabel *cl = nil; 
cl = (UILabel*)[cell.contentView viewWithTag:2000]; 
if(!cl) 
{ 
    cl = [[UILabel alloc] initWithFrame:CGRectMake(10,10,100,30)]; 
    cl.tag = 2000; 
    [cell.contentView addSubview:cl]; 
} 
if(beforeButtonPressed) 
cl.textColor = [UIColor blackColor]; 
else if (afterButtonPressed) 
cl.textColor = [UIColor blueColor]; 

我想上述方式将是您的要求的解决方案。

+0

我也只做了这个。但是,我收到以下错误警告:试图创建USE_BLOCK_IN_FRAME变量块不在框架中后,我按下按钮和文本颜色也没有得到更新。你能帮我吗? – user574089

+0

在cellForRowAtIndexPath数据源方法中完成以下{UILabel * lblInstructionTitle = [[UILabel alloc] init]; if(ColorIsSetToBlack) { lblInstructionTitle.textColor = [UIColor redColor]; } else { \t lblInstructionTitle.textColor = [UIColor whiteColor];} [cell。contentview addsubview:lblInstructionTitle];} ColorIsSetToBlack是一个布尔值,它设置在点击按钮上,然后调用tableview reloaddata方法。你能否告诉我我是否正确行事? – user574089

+0

我已经更新了我的答案。在'cellForRowAtIndexPath'方法中返回单元格之前添加代码。 – Ilanchezhian