简体   繁体   中英

Change UIButton Color in UITableViewCell onload

I have a list of contacts, app can add/view details. I added a star button in my custom UITableViewCell, It is for "Favorites" functionality. I want my button to be color yellow if the contact is 'Favorited' and Gray if not. Here is my code.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier
                                                           forIndexPath:indexPath];

ContactUtilities *cu = [[ContactUtilities alloc]init];

NSMutableDictionary *listToUse = [NSMutableDictionary new];

if([self.txtSearchContacts.text isEqualToString:@""]){
    listToUse = self.contactList;
} else {
    listToUse = searchContactList;
}


NSArray *keyList = [listToUse allKeys];
NSString *search = [keyList objectAtIndex:indexPath.row];
Contact *contact = [[Contact alloc]init];
contact = [cu searchContact:search :listToUse];

//Tagging
UILabel *lblContactName    = [cell.contentView viewWithTag:ContactCellElementName];
UIImageView *imgContactPic = [cell.contentView viewWithTag:ContactCellElementImage];
UILabel *lblContactCompany = [cell.contentView viewWithTag:ContactCellElementCompany];
UILabel *lblContactNumber  = [cell.contentView viewWithTag:ContactCellElementNumber];
UIButton *isFavorite       = (UIButton *)[cell viewWithTag:ContactCellElementButton];

UIImage* image = [UIImage imageNamed:contact.imageName];

CGImageRef cgref = [image CGImage];
CIImage *cim = [image CIImage];

if (cim == nil && cgref == NULL)
{
    image = [UIImage imageNamed:@"Person"];
}

lblContactName.text    = contact.contactName;
imgContactPic.image    = image;
lblContactCompany.text = contact.contactCompanyName;
lblContactNumber.text  = contact.contactPhoneNumber;

//This is where it doesn't work..
if([contact.isFavorite isEqualToString:@"YES"]){
    [isFavorite setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
} else {
    [isFavorite setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
}

//I also have a property that will check if you will show the button. This is working already.

if([contact.shouldShow isEqualToString:@"No"]){
    [isFavorite removeFromSuperview];
}

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}

That is my cellForRowAtIndexPath code. I am currently trying the setTitleColor property but it doesn't work. Same as the setTintColor it doesn't work either.

Tint color is what you want, but it only works if the image is a PNG with an alpha channel, and the rendering mode of the image is set to template. Refer to this answer . If you're assigning the image to the button in a storyboard, you can set the rendering mode in the asset library .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM