Changing elements in selected UITableViewCell subclass - objective-c

I have implemented a custom UITableViewCell for my application and have created a custom background view and selectedbackgroundview, both of which work great. However, I have several other images and uilabels on the cell that I want to change the color's of when it is selected. I have overwritten the following method and it logs correctly when the cell is selected but it does not change the image or the text color.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
if (selected) {
NSLog(#"setSelected:YES");
separatorImage.image = [UIImage imageNamed:#"SeparatorSelected"];
titleLabel.textColor = [UIColor whiteColor];
} else {
NSLog(#"setSelected:NO");
separatorImage.image = [UIImage imageNamed:#"Separator"];
titleLabel.textColor = [UIColor grayColor];
}
}
Any Idea what I am doing wrong?
Update
separatorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Separator"]]];
[separatorImage setFrame:CGRectMake(99, 4, 5, 71)];
separatorImage.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:separatorImage];
titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(111, 4, 188, 26)];
titleLabel.font = [UIFont fontWithName:#"Arial Rounded MT Bold" size:21.0];
titleLabel.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:titleLabel];

I have a hunch that sending -setSelected:animated: to super at the beginning of the method is preventing the changes to your cell. Try moving the call to super to the end of the method. You should also override -setHighlighted:animated: or your selection will appear to lag.

Related

Two lines of text on UIButton with different fonts each

I found a way to add two lines of text on a UIButton,
but what I want is that each of these lines of texts
have different font (for instance one is bold, other not).
How is it possible to do this?
Thanks.
You should add 2 UILabel to the UIButton as subviews.
You can do it like:
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeCustom];
testButton.frame = CGRectMake(0, 0, 200, 40);
[self.view addSubview:testButton];
UILabel *firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
firstLineTestButton.text = #"First line";
firstLineTestButton.font = [UIFont systemFontOfSize:12];
[testButton addSubview:firstLineTestButton];
UILabel *secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
secondLineTestButton.text = #"Second line";
secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[testButton addSubview:secondLineTestButton];
To also make highlighting possible for the UILabels, you need to make the highlighting of the button custom.
So add the actions to the button and then check the button subviews for the labels and change their colors.
[testButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[testButton addTarget:self action:#selector(changeColor:) forControlEvents:UIControlEventTouchDown];
[testButton addTarget:self action:#selector(touchCancel:) forControlEvents:UIControlEventTouchDragExit];
-(void)buttonAction:(UIButton*)sender
{
[self touchCancel:sender];
/* DO SOME MORE ACTIONS */
}
-(void)changeColor:(UIButton*)sender
{
sender.backgroundColor = [UIColor grayColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blueColor];
}
}
}
-(void)touchCancel:(UIButton*)sender
{
sender.backgroundColor = [UIColor clearColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blackColor];
}
}
}
The solution of Roland is good, another way to do this would be to use a NSAttributedString. The downside is, that it only works in iOS 6 and above.
If this is not a problem, here is the code
- (void)viewDidLoad
{
[super viewDidLoad];
// We want 2 lines for our buttons' title label
[[self.button titleLabel] setNumberOfLines:2];
// Setup the string
NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:#"This should be bold,\n and this should not."];
// Set the font to bold from the beginning of the string to the ","
[titleText addAttributes:[NSDictionary dictionaryWithObject:[UIFont boldSystemFontOfSize:14] forKey:NSFontAttributeName] range:NSMakeRange(0, 20)];
// Normal font for the rest of the text
[titleText addAttributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName] range:NSMakeRange(20, 22)];
// Set the attributed string as the buttons' title text
[self.button setAttributedTitle:titleText forState:UIControlStateNormal];
}
You can add two UILabels as subview of the button and then can set the text of the labels as
[lbl1 setFont:[UIFont fontWithName:#"Arial-Bold" size:18]];
[lbl2 setFont:[UIFont fontWithName:#"Arial" size:16]];
For proper animation, you should subclass UIButton and redraw it when its state changes.
(void)drawRect:(CGRect)rect
{
if (!self.firstLineTestButton) {
self.firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
self.firstLineTestButton.text = #"First line";
self.firstLineTestButton.font = [UIFont systemFontOfSize:12];
[self addSubview:self.firstLineTestButton];
}
if (!self.secondLineTestButton) {
self.secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
self.secondLineTestButton.text = #"Second line";
self.secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[self addSubview:self.secondLineTestButton];
}
if (!self.highlighted) {
// Do custom drawing such as changing text color
} else {
// Do custom drawing such as changing text color
}
}
(void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
// Force redraw of button
[self setNeedsDisplay];
}

custom tableview and highlightedTextColor

i have a table view, with custom cell, i have set the cell for have a highlighted color on text when you tap on it.
//cell specific
NSString *ligneTableau = [NSString stringWithFormat:#"%#", [[table objectAtIndex:indexPath.row] nome]];
cell.label.text = ligneTableau;
cell.label.font = [UIFont fontWithName:#"populaire" size:35];
cell.label.textColor = [UIColor colorWithRed:124.0f/255.0f green:153.0f/255.0f blue:106.0f/255.0f alpha:1.0f];
cell.fondo.image = [UIImage imageNamed: #"cell_ant.png"];
//highlighted Text
cell.label.highlightedTextColor = [UIColor colorWithRed:55.0f/255.0f green:70.0f/255.0f blue:48.0f/255.0f alpha:1.0f];
every things work fine, but when come back to the table the text stay highlighted.
I forget somethings?
Probably the cell remains selected when you go back to table. So as soon as come back to table you should set deselected.
[cell setSelected:NO];
In your UpdatesTableViewCell class, you can implement the following methods:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
[super setHighlighted:highlighted animated:animated];
if (highlighted)
self.label.textColor = [UIColor colorWithRed:55.0f/255.0f green:70.0f/255.0f blue:48.0f/255.0f alpha:1.0f];
else
self.label.textColor = [UIColor colorWithRed:124.0f/255.0f green:153.0f/255.0f blue:106.0f/255.0f alpha:1.0f];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
if (selected)
self.label.textColor = [UIColor colorWithRed:55.0f/255.0f green:70.0f/255.0f blue:48.0f/255.0f alpha:1.0f];
else
self.label.textColor = [UIColor colorWithRed:124.0f/255.0f green:153.0f/255.0f blue:106.0f/255.0f alpha:1.0f];
}

UINavigationBar styling issue?

I have a UINavigationBar I am having style issues. To start out, I use this code (a class inside my navigation controller) to style my UINavigationBar.
#import...
#implementation UINavigationBar (UINavigationBarCustomDraw)
- (void) drawRect:(CGRect)rect {
[self setTintColor:[UIColor colorWithRed:0.9f green: 0.9f blue:0.9f alpha:1]];
if ([self.topItem.title length] > 0 && ![self.topItem.title isEqualToString:#"Back to ..."]) {
[[UIImage imageNamed:#"UINavigationBar_background.png"] drawInRect:rect];
CGRect frame = CGRectMake(0, 0, 320, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
[label setBackgroundColor:[UIColor clearColor]];
label.font = [UIFont boldSystemFontOfSize: 20.0];
label.shadowColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor colorWithRed:(70.0 / 255.0) green:(70.0 / 255.0) blue:(70.0 / 255.0) alpha: 1];
label.text = self.topItem.title;
self.topItem.titleView = label;
} else {
//[[UIImage imageNamed:#"login_button.png"] drawInRect:rect];
self.topItem.titleView = [[[UIView alloc] init] autorelease];
}
}
#end
#implementation...
Here's my two issues:
When I apply this code in another document with different form and styles, it changes everything. Why is this happening?
When moving from one view to another, the textColor changes to white. It shows great on start up and when I go back in the navigation controller it works fine.
Thanks in advance!
PS: If you need any more code, please ask!

Loading data issue in UITableview

I created an application using UITableView. I parsing the data from URL and listed in UITableView.
But in UITableView, the first the data only displayed again and again.
I don't know why this problem occurred.
My code is as below:
-(UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
CGRect frame = CGRectMake(10.0f, 5.0, 300.0, 55);
valueField = [[UILabel alloc] initWithFrame:frame];
[valueField setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
valueField.tag = 111;
valueField.font=[UIFont fontWithName:#"Helvetica" size:16.0];
valueField.textAlignment = UITextAlignmentLeft;
valueField.lineBreakMode=UILineBreakModeWordWrap;
valueField.numberOfLines = 0;
valueField.textColor = [UIColor whiteColor];
valueField.highlightedTextColor = [UIColor whiteColor];
valueField.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
valueField.adjustsFontSizeToFitWidth = YES;
valueField.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
valueField.text=[title1 objectAtIndex:count1];
[cell.contentView addSubview:valueField];
UIImage *favOn = [UIImage imageNamed:#""];
UIImage *favOff = [UIImage imageNamed:#""];
titlebutton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, 15.0, 300.0, 55)];
[titlebutton setTag:indexPath.row];
//titlebutton.tag = 111;
[titlebutton setImage:favOff forState:UIControlStateNormal];
[titlebutton setImage:favOn forState:UIControlStateSelected];
if([self getFavState:#"111"])
{
[titlebutton setSelected:YES];
}
else
{
[titlebutton setSelected:NO];
}
[titlebutton addTarget:self action:#selector(favButtonSwitch:) forControlEvents:UIControlEventTouchUpInside];
[titlebutton setBackgroundColor:[UIColor clearColor]];
[titlebutton setTitle:#"" forState:UIControlStateNormal];
[cell.contentView addSubview:titlebutton];
CGSize labelSize = [valueField.text sizeWithFont:valueField.font constrainedToSize:valueField.frame.size lineBreakMode:UILineBreakModeWordWrap];
int labelHeight = labelSize.height;
NSLog(#"labelHeight = %d", labelHeight);
frame = CGRectMake(10.0f, 40.0, 300.0, 55);
pubField = [[UILabel alloc] initWithFrame:frame];
[pubField setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
pubField.tag = 111;
pubField.font=[UIFont fontWithName:#"Helvetica" size:12.0];
pubField.textAlignment = UITextAlignmentLeft;
pubField.lineBreakMode=UILineBreakModeWordWrap;
pubField.numberOfLines = 0;
pubField.textColor = [UIColor whiteColor];
pubField.highlightedTextColor = [UIColor whiteColor];
pubField.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
pubField.adjustsFontSizeToFitWidth = YES;
pubField.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
pubField.text=[pubDate objectAtIndex:indexPath.row];
[cell.contentView addSubview:pubField];
frame = CGRectMake(5.0, 70.0, 300.0, 55);
desField = [[UILabel alloc] initWithFrame:frame];
[desField setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
desField.tag = 111;
desField.font=[UIFont fontWithName:#"Helvetica" size:13.0];
desField.textAlignment = UITextAlignmentLeft;
desField.lineBreakMode=UILineBreakModeWordWrap;
desField.numberOfLines = 0;
desField.textColor = [UIColor whiteColor];
desField.highlightedTextColor = [UIColor whiteColor];
desField.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
desField.adjustsFontSizeToFitWidth = YES;
desField.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
desField.text=[description objectAtIndex:indexPath.row];
[cell.contentView addSubview:desField];
}
UIImage *patternImage = [UIImage imageNamed:#"bg.jpg"];
UIView *backView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
backView.backgroundColor = [UIColor colorWithPatternImage: patternImage];
cell.backgroundView = backView;
NSString *image1 =[images objectAtIndex:indexPath.row];
NSLog(#"Images ..... = %#",image1);
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[images objectAtIndex:indexPath.row]]];
UIImage *myimage = [[UIImage alloc] initWithData:mydata];
UIImageView *imageView = [ [ UIImageView alloc ] initWithImage: myimage ];
imageView.frame = CGRectMake(10.0f, 110.0f, 120.0f, 120.0f);
[cell.contentView addSubview:imageView];
return cell;
}
do all the alloc/init and all things, that will be the same in any cell in the
if(cell==nil){
//<-- here
}
while setting text and any thing that changes by the specific data outside the block
if(cell==nil){
}
//<-- here
i.e:
if(cell==nil){
//....
valueField.tag = 111;
valueField.font = [UIFont fontWithName:# "Helvetica" size:16.0];
valueField.textAlignment = UITextAlignmentLeft;
valueField.lineBreakMode = UILineBreakModeWordWrap;
valueField.numberOfLines = 0;
valueField.textColor = [UIColor whiteColor];
valueField.highlightedTextColor = [UIColor whiteColor];
valueField.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
valueField.adjustsFontSizeToFitWidth = YES;
valueField.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
[cell.contentView addSubview : valueField];
//....
}
//....
valueField.text = [title1 objectAtIndex:count1];
//....
the first cell data is getting displayed in all the cells because when you initialize and create your reusable cell, you fill the data there, you need to initialize a reusable cell that doesnt have all its values set, and then set this information for each cell. That is, you need to have all the information you want for each particular cell outside the if(cell==nil) part of this code, and rely on the indexPath to know which cell you are in, and feed in different data based on this.
You seem to be constructing the subviews of the cell correctly when there is no reusable cell available. The question is, what does your code do when you do dequeue a reusable cell? It appears that you do nothing. You should move any row-specific initialization (setting label text values, images, etc.) outside the check for whether the dequeued cell is nil. In this way, whether you just constructed a new cell or dequeued a previously-created cell, the data being displayed correctly correlates to the row being displayed.
Well actually your code this way is quite hard to decode,
but first of all, you declare a lot of tag that should be used to retrieve the UIViews you're declaring.
Unfortunately these are all the same (tags) so you might never get what you want. You should maybe put in some constant in your header file like:
#define kPubLabel 100
then use them.
then you usually retrieve these after declaring your cell to populate them.
In the mean time, retrieving your images from url in this method is one of the best way to have your application being slow, since each time you scroll, you'll have to re-fetch your image from where it come from causing your table view to "freeze".
Finally, the only thing that might change, according to your code is the imageView that you add to your frame. You usually have an ImageView in which you put an image that you might have stored/cached but rarely change the contentView of a cell.
ie
Maybe you should externalize your cell building code in a class overriding UITableViewCell.
Put different tags on every element in your cell to retrieve them in your method.
Retrieve your elements in your method according to there tags.
Populate and only populate them in your method.
Retrieve your image once and for all for performance improval.
I'm not sure this will help, but in my point of view, there are actually a lot work to do in your code.

How Can I Set the Height of a Single UITabelViewCell to a Constant Value?

I am searching on Google about this but I always find very complex solutions about it. I have a cell with an non editable scrollable UITextView and I just want to increase the height of that cell to a constant value. How can I do it? Actually I am using the next code to add the UITextView to the cell.
cell.contentView.bounds = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
UITextView *textView = [[UITextView alloc] initWithFrame:cell.contentView.bounds];
textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
textView.editable = NO;
textView.scrollEnabled = YES;
textView.backgroundColor = [UIColor clearColor];
textView.text = self.description;
[cell.contentView addSubview:textView];
[textView release];
Thanks for reading.
Implement this method in your delegate: http://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForRowAtIndexPath: