Changing the text color of UILabel in UITableViewCell

匆匆过客 提交于 2019-12-13 08:37:40

问题


I am required to change the text color of the UILabel which is contained in the UITableViewCell on a button click. I have created a UIColor object, which is set to specified color on the button click and called the UITableView reloadData method, even then the color is not changing. How should I implement this?


回答1:


I assume that you want to change the color of all rows in your table. (If you just want to change a single row, you will need its indexPath).

Create a BOOL variable that keeps track of the color state. In your button click routine, set this value appropriately and do a [tableView reloadData].

In cellForRowAtIndexPath you need to check the variable and set the color for both states each time. It is essential that you do it both ways, otherwise the state of the cell will be unpredictable when scrolling.




回答2:


For changing the text color of a UITableViewCell, you have to implement the UITableViewDataSource delegator function

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

In there, you get the cell with


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

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

And here you can change the text's color.

BTW: You should accept some answers you get to your questions - that will raise your chances to get answers for future questions ...




回答3:


Fine, while you add the custom UILabel to the contentView, set a tag for the 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];

I guess the above way would be a solution for your requirement.



来源:https://stackoverflow.com/questions/7872124/changing-the-text-color-of-uilabel-in-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!