How to set UIlabel TextColor Dynamically - iphone

I have created more than one label using this code,
.H file
#interface ViewController : UIViewController
{
NSArray * phraseAry ;
UIView * containerView;
UILabel * oldLabel;
NSMutableArray *dataArray;
}
#property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
.M file
- (void)viewDidLoad
{
[super viewDidLoad];
heightValue = 20;
widthValue = 0;
xValue = 5;
yValue = 10;
containerView = [[UIView alloc] init];
for (int i=0; i<phraseAry.count; i++) {
widthValue = [self returnWidth:[phraseAry objectAtIndex:i]];
int newXValue = xValue+widthValue+5;
//NSLog(#"newXValue : %i",newXValue);
if (newXValue > 310) {
yValue +=20;
xValue = 5;
newXValue = xValue+widthValue+5;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(xValue, yValue, widthValue, heightValue)];
lbl.text = [phraseAry objectAtIndex:i];
[lbl setFont:[UIFont fontWithName:#"Helvetica" size:14.0]];
lbl.tag = i;
lbl.textColor = [UIColor colorWithRed:(92/255.0) green:(109/255.0) blue:(43/255.0) alpha:1];
[containerView addSubview:lbl];
xValue = newXValue;
} else {
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(xValue, yValue, widthValue, heightValue)];
lbl.text = [phraseAry objectAtIndex:i];
[lbl setFont:[UIFont fontWithName:#"Helvetica" size:14.0]];
lbl.tag = i;
lbl.textColor = [UIColor colorWithRed:(92/255.0) green:(109/255.0) blue:(43/255.0) alpha:1];
[containerView addSubview:lbl];
xValue = newXValue;
}
}
containerView.frame = CGRectMake(0, 0, 320, yValue);
//add code to customize, e.g. polygonView.backgroundColor = [UIColor blackColor];
[self.myScrollView addSubview:containerView];
self.myScrollView.contentSize = containerView.frame.size;
}
And than i set background color and textcolor in specific table using this code
- (void)updateLabelMethod
{
oldLabel.backgroundColor = [UIColor clearColor];
UILabel *label = (UILabel *)[containerView viewWithTag:2];
oldLabel = label;
label.backgroundColor = [UIColor colorWithRed:(98/255.0) green:(147/255.0) blue:(216/255.0) alpha:1];
label.textColor = [UIColor whiteColor];
containerView.backgroundColor = [UIColor clearColor];
}
It will update background of label fine but when i use this code to update textcolor it will display error like this
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setTextColor:]: unrecognized selector sent to instance 0xbaa3b30'
Any ways to set textcolor? Plz help.

Start your label tag from 1 instead of 0, because by default the tag value is 0 for all view.
lbl.tag = i+1;
Because
UILabel *label = (UILabel *)[containerView viewWithTag:0];
it will return containerView itself, and UIView not have textColor property :P

[containerView viewWithTag:2];
check container view has only one view that is a label with tag 2.
May be some other view is set with tag 2 and may be causing the issue.
NSLog(#"%#",label);
can give you what the label here gives the output .It should point out an UILabel itself
make use of isKindOfClass: to identify it is a label you are updating

for (UILable *lblTemp in containerView.subviews){
if ([lblTemp isKindOfClass:[UILable class]] && lblTemp.tag==2){
// change the lbl color
break;
}
}
check using this code ;)

Related

UISwitch puts on UILabel event doesn't work

I encounter a problem is that I need a formatted grid which contain serious of UISwitch, and my solution is to put those UISwitches on each UILabel .
However, these switches can't operate normally. Any suggestions?
Below is my code:
-(void) drawSummaryColumn : (UILabel *) myLabel :(NSString *) title
{
NSArray *sHeaders = #[NSLocalizedString(#"Tue", nil),
NSLocalizedString(#"Wed", nil),
NSLocalizedString(#"Thu", nil),
NSLocalizedString(#"Fri", nil),
NSLocalizedString(#"Sat", nil),
NSLocalizedString(#"Sun", nil),
NSLocalizedString(#"Total", nil)];
float basizSize = myLabel.frame.size.width;
CGRect r;
CGRect pos;
pos.origin.x =8;
pos.origin.y = 3;
UILabel *firstCol = [[UILabel alloc] initWithFrame:CGRectZero];
r.origin.x =0.5;
r.origin.y =0.5;
r.size = CGSizeMake(120, 40);
firstCol.text =title;
firstCol.font = [ UIFont fontWithName :#"Georgia-Bold" size : 17];
firstCol.backgroundColor = [UIColor whiteColor];
firstCol.textAlignment = NSTextAlignmentCenter;
firstCol.frame =r ;
[myLabel addSubview:firstCol ];
basizSize -= 120;
basizSize = (float) basizSize / 7;
for (NSString *label in sHeaders)
{
UISwitch *objSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
objSwitch.frame = pos;
[objSwitch addTarget:self action:#selector(switchAction:) forControlEvents:UIControlEventValueChanged];
UILabel *columns = [[UILabel alloc] initWithFrame:CGRectZero];
columns.backgroundColor = [UIColor whiteColor];
columns.textAlignment = NSTextAlignmentCenter;
[columns addSubview:objSwitch];
r.origin.x += r.size.width + 0.5f;
r.size = CGSizeMake(basizSize, 40);
columns.frame =r ;
[myLabel addSubview:columns];
}
}
try
myLabel.userInteractionEnabled = YES;
firstCol.userInteractionEnabled = YES;
columns.userInteractionEnabled = YES;
by default, a label's userInteraction property is false. Hence all it's subviews(including uiswitch) has this property set to FALSE initially. parent view (uilabel) needs to have this property ENABLED so that it's subviews also get enabled for user interaction.

Vertically align text in a UILabel

I am new to iPhone,
How do I vertically align my text in the UILabel?
Here is my Code snippet,
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,100,100);
lbl.backgroundColor=[UIColor clearColor];
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"123456";
[scrollVw addSubview:lbl];
text displayed is in the format of 123456 but i want text should be display vertically like,
6
5
4
3
2
1
Any help will be appriciated.
Its impossible to align the text in UILabel vertically. But, you can dynamically change the height of the label using sizeWithFont: method of NSString, and just set its x and y as you want.
As an alternative you can use UITextField. It supports the contentVerticalAlignment peoperty as it is a subclass of UIControl. You have to set its userInteractionEnabled to NO to prevent user from typing text on it.
EDIT 1
Well instead of a UILabel , Make a UITableView like :-
TableActivityLevel=[[UITableView alloc] initWithFrame:CGRectMake(224, 203, 27, 0) style:UITableViewStylePlain];
TableActivityLevel.delegate=self;
TableActivityLevel.dataSource=self;
TableActivityLevel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
TableActivityLevel.rowHeight = 17;
TableActivityLevel.backgroundColor=[UIColor clearColor];
TableActivityLevel.layer.borderColor = [[UIColor clearColor]CGColor];
TableActivityLevel.separatorStyle = UITableViewCellSeparatorStyleNone;
EDIT 2 Found the method using UILabels too !! :) Check this out....
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, 10.0, 100.0)];
[label1 setBackgroundColor:[UIColor clearColor]];
[label1 setNumberOfLines:0];
[label1 setCenter:self.view.center];
[label1 setFont:[UIFont fontWithName:#"Helvetica" size:12.0]];
[label1 setTextColor:[UIColor whiteColor]];
[label1 setTextAlignment:UITextAlignmentCenter];
[label1 setText:#"1 2 3 4 5 6"];
[self.view addSubview:label1];
If it just a single lined text as in your example you can use various workarounds. I personally would create a UILabel subclass as follows,
#implementation VerticalLabel
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.numberOfLines = 0;
}
return self;
}
- (void)setText:(NSString *)text {
NSMutableString *newString = [NSMutableString string];
for (int i = text.length-1; i >= 0; i--) {
[newString appendFormat:#"%c\n", [text characterAtIndex:i]];
}
super.text = newString;
}
#end
You now just have to replace
UILabel *lbl = [[UILabel alloc] init];
with
UILabel *lbl = [[VerticalLabel alloc] init];
to get vertical text.
Hi the following code is work well
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,10,300);
lbl.backgroundColor=[UIColor clearColor];
lbl.numberOfLines=6; // Use one to 6 numbers
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"123456";
NSString *reverse=lbl.text;
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [reverse length];
while (charIndex > 0) {
charIndex--;
NSRange subStrRange = NSMakeRange(charIndex, 1);
[reversedString appendString:[reverse substringWithRange:subStrRange]];
}
NSLog(#"%#", reversedString);
CGSize labelSize = [lbl.text sizeWithFont:lbl.font
constrainedToSize:lbl.frame.size
lineBreakMode:lbl.lineBreakMode];
lbl.frame = CGRectMake(
lbl.frame.origin.x, lbl.frame.origin.y,
lbl.frame.size.width, labelSize.height);
lbl.text=reversedString;
[scrollview addSubview:lbl];
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,10,100);
lbl.backgroundColor=[UIColor clearColor];
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"123456";
lbl.numberOfLines = 10;
[self.view addSubview:lbl];
You cant do vertical allignment but use another way to display it
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,100,400);
lbl.backgroundColor=[UIColor clearColor];
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"1\n2\n3\n4\n5\n6";
[scrollVw addSubview:lbl];

uiimageview gets nil and hence code crashes

in this block of code my uiimageview always get nil.as a result the code crashes.i can t figure out where is the uiimageview getting nil.in this code self refers to uitableviewcell.
the code crashes in the code where i am inserting the imageview to the array.is this a problem of memory retain?
MyAppDelegate *appDelegate =(myAppDelegate *)[[UIApplication sharedApplication]delegate];
UIImageView *profileImageView;
UILabel *tweetLabel;
UILabel *timeLabel;
UILabel *profileNameLabel;
UIView *message;
if(self==nil)
{
profileImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
profileImageView.backgroundColor= [UIColor clearColor];
profileImageView.tag = 1;
tweetLabel = [[UILabel alloc] initWithFrame:CGRectZero];
tweetLabel.backgroundColor = [UIColor clearColor];
tweetLabel.tag = 2;
tweetLabel.numberOfLines = 3;
tweetLabel.lineBreakMode = UILineBreakModeWordWrap;
tweetLabel.font = [UIFont systemFontOfSize:10.0];
tweetLabel.textColor=[UIColor blackColor];
timeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
timeLabel.backgroundColor = [UIColor clearColor];
timeLabel.tag = 3;
timeLabel.numberOfLines = 1;
timeLabel.lineBreakMode = UILineBreakModeWordWrap;
timeLabel.font = [UIFont systemFontOfSize:12.0];
timeLabel.textColor=[UIColor blackColor];
profileNameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
profileNameLabel.backgroundColor = [UIColor clearColor];
profileNameLabel.tag = 4;
profileNameLabel.numberOfLines = 1;
profileNameLabel.lineBreakMode = UILineBreakModeWordWrap;
profileNameLabel.font = [UIFont boldSystemFontOfSize:14.0];
profileNameLabel.textColor=[UIColor blackColor];
message = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height)];
message.tag = 0;
[message addSubview:profileImageView];
[message addSubview:tweetLabel];
[message addSubview:timeLabel];
[message addSubview:profileNameLabel];
[self addSubview:message];
}
else{
tweetLabel = (UILabel *)[[self.contentView viewWithTag:0]viewWithTag:2];
timeLabel = (UILabel *)[[self.contentView viewWithTag:0]viewWithTag:3];
profileNameLabel = (UILabel *)[[self.contentView viewWithTag:0]viewWithTag:4];
profileImageView = (UIImageView *)[self.contentView viewWithTag:1];
NSLog(#" profileImageView %#",profileImageView);
}
NSString *tweet=[tweetObject tweet];
NSString *profileName=[tweetObject author];
NSString *time=[tweetObject time];
CGSize textSize = [tweet sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(240.0f, 480.0f) lineBreakMode:UILineBreakModeWordWrap];
CGSize timeSize = [time sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(240.0f, 480.0f) lineBreakMode:UILineBreakModeWordWrap];
CGSize profileNameSize = [profileName sizeWithFont:[UIFont boldSystemFontOfSize:14.0] constrainedToSize:CGSizeMake(240.0f, 480.0f) lineBreakMode:UILineBreakModeWordWrap];
profileImageView.frame = CGRectMake(5,self.frame.size.height/2, 44, 44);
NSLog(#" profileImageView %#",profileImageView);
tweetLabel.frame = CGRectMake(54, profileImageView.frame.size.width, 240,25);
timeLabel.frame = CGRectMake(180, 5.0f, 100, timeSize.height);
profileNameLabel.frame = CGRectMake(54,5, 150, profileNameSize.height);
tweetLabel.text=tweet;
timeLabel.text=time;
profileNameLabel.text=profileName;
profileImageView.image = [[UIImage imageNamed:#"fbdefaultProfile.gif"]retain];
NSLog(#" myArray WILL FILL WITH THIS ELEMNTS %# %# %# ",profileImageView,[tweetObject imageURL],#"fbdefaultProfile.gif");
NSArray *myArray = [NSArray arrayWithObjects:profileImageView,[tweetObject imageURL],#"fbdefaultProfile.gif",nil];
NSLog(#" myArray %#",myArray);
NSLog(#"%# myArray ",myArray);
[appDelegate performSelectorInBackground:#selector(updateImageViewInBackground:) withObject:myArray];
}
return;
if(self==nil)
{
what is this.. I think it should be
if(self!=nil)
{
and if it is fine then why are you adding subview to a nill
if(self==nil)
{
//your code .....
//and then you are adding sub view to a nil which is useless
[self addSubview:message];
}
The issue could be in the below line of code.
profileImageView = (UIImageView *)[self.contentView viewWithTag:1];
May be you don't have the an view with tag id 1;
plz check against nil after getting the view from viewWithTag.
if([self.contentView viewWithTag:1] != nil)
{
profileImageView = (UIImageView *)[self.contentView viewWithTag:1];
}

UITableView with columns

I need to display a list items in a tableview but with about 5 different columns similar to a spreadsheet. The last column would be a UIButton (which I know is possible).
Is it possible to achieve this type of design with the UITableView?
I found an easier way of doing this by following one of Apple's samples:
- (UITableViewCell *)tableViewCellWithReuseIdentifier:(NSString *)identifier {
/*
Create an instance of UITableViewCell and add tagged subviews for the name, local time, and quarter image of the time zone.
*/
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
/*
Create labels for the text fields; set the highlight color so that when the cell is selected it changes appropriately.
*/
UILabel *label;
CGRect rect;
// Create a label for the time zone name.
rect = CGRectMake(LEFT_COLUMN_OFFSET, (ROW_HEIGHT - LABEL_HEIGHT) / 2.0, LEFT_COLUMN_WIDTH, LABEL_HEIGHT);
label = [[UILabel alloc] initWithFrame:rect];
label.tag = NAME_TAG;
label.font = [UIFont boldSystemFontOfSize:MAIN_FONT_SIZE];
label.adjustsFontSizeToFitWidth = YES;
[cell.contentView addSubview:label];
label.highlightedTextColor = [UIColor whiteColor];
[label release];
// Create a label for the time.
rect = CGRectMake(MIDDLE_COLUMN_OFFSET, (ROW_HEIGHT - LABEL_HEIGHT) / 2.0, MIDDLE_COLUMN_WIDTH, LABEL_HEIGHT);
label = [[UILabel alloc] initWithFrame:rect];
label.tag = TIME_TAG;
label.font = [UIFont systemFontOfSize:MAIN_FONT_SIZE];
label.textAlignment = UITextAlignmentRight;
[cell.contentView addSubview:label];
label.highlightedTextColor = [UIColor whiteColor];
[label release];
// Create an image view for the quarter image.
rect = CGRectMake(RIGHT_COLUMN_OFFSET, (ROW_HEIGHT - IMAGE_SIDE) / 2.0, IMAGE_SIDE, IMAGE_SIDE);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
imageView.tag = IMAGE_TAG;
[cell.contentView addSubview:imageView];
[imageView release];
return cell;
}
A customized workaround, you can make your own table cells this way:
#interface MyOwnCell : UITableViewCell {
NSMutableArray *columns;
}
- (void)addColumn:(CGFloat)position;
#end
#implementation MyOwnCell
- (void)addColumn:(CGFloat)position {
[columns addObject:[NSNumber numberWithFloat:position]];
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0);
CGContextSetLineWidth(ctx, 0.25);
for (int i = 0; i < [columns count]; i++) {
CGFloat f = [((NSNumber*) [columns objectAtIndex:i]) floatValue];
CGContextMoveToPoint(ctx, f, 0);
}
[super drawRect:rect];
}
#end
Refer to TheLearner's solution which is actually more easier :)

UINavigationItem titleView position

I'm using UINavigationItem's titleView property to set a custom UILabel with my desired font size/color. Here's my code:
self.headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 400.0, 44.0)];
self.headerLabel.textAlignment = UITextAlignmentCenter;
self.headerLabel.backgroundColor = [UIColor clearColor];
self.headerLabel.font = [UIFont boldSystemFontOfSize:20.0];
self.headerLabel.textColor = [UIColor colorWithRed:0.259 green:0.280 blue:0.312 alpha:1.0];
self.navigationItem.titleView = self.headerLabel;
In the navigation bar I also have a left bar button. The result is: the text isn't properly centered. I've tried setting the x origin of the label, but this has no effect.
In stead of initWithFrame just use init and put [self.headerLabel sizeToFit] after your last line of code.
If you make the headerLabel a subview of the titleView, you can then set headerLabel's frame to control where it goes within the titleView.
The way you are doing it now, you don't have that control. I think the OS chooses the titleView's frame for you based on the space available.
Hope this helps!
I've used custom title labels for my nav bars in every app I have in the app store. I've tested many different ways of doing so and by far the easiest way to use a custom label in a navigation bar is to completely ignore titleView and insert your label directly into navigationController.view.
With this approach, it's easy to have the title label's frame always match the navigationBar's frame -- even if you are using a custom navBar with a non-standard size.
- (void)viewDidLoad {
[self.navigationController.view addSubview:self.titleLabel];
[super viewDidLoad];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)didRotateFromInterfaceOrientation:
(UIInterfaceOrientation)fromInterfaceOrientation {
[self frameTitleLabel];
}
- (UILabel *) titleLabel {
if (!titleLabel) {
titleLabel = [[UILabel alloc]
initWithFrame:self.navigationController.navigationBar.frame];
titleLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18];
titleLabel.text = NSLocalizedString(#"Custom Title", nil);
titleLabel.textAlignment = UITextAlignmentCenter;
titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
}
return titleLabel;
}
- (void) frameTitleLabel {
self.titleLabel.frame = self.navigationController.navigationBar.frame;
}
The one caveat to this approach is that your title can flow over the top of any buttons you have in the navBar if you aren't careful and set the title to be too long. But, IMO, that is a lot less problematical to deal with than 1) The title not centering correctly when you have a rightBarButton or 2) The title not appearing if you have a leftBarButton.
I have a same problem; I just somehow solved this issue by calculating the title length and set the label frame width accordingly. Although this is not a perfect one but can be manageable. Here is the code.
label = [[UILabel alloc] init];
label.backgroundColor = [UIColor clearColor];
label.font = [ UIFont fontWithName: #"XXII DIRTY-ARMY" size: 32.0 ];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.0f];
label.textAlignment = UITextAlignmentCenter;
label.textColor =[UIColor orangeColor];
//label.text=categoryTitle;
CGFloat verticalOffset = 2;
NSString *reqSysVer = #"5.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
{
if (categoryTitle.length > 8)
{
label.frame = CGRectMake(0, 0, 300, 44);
}else {
label.frame = CGRectMake(0, 0, 80, 44);
}
self.navigationItem.titleView = label;
self.navigationItem.title=label.text;
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:verticalOffset forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTintColor:[UIColor newBrownLight]];
}
Just calculate exact frame size needed and align to left:
UIFont* font = [UIFont fontWithName:#"Bitsumishi" size:20];
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [title sizeWithFont:font constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeCharacterWrap];
CGRect frame = CGRectMake(0, 0, expectedLabelSize.width, expectedLabelSize.height);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.font = font;
label.textAlignment = UITextAlignmentLeft;
label.text = title;
self.titleView = label;
UIView *vw = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
lbl.text = #"Home";
lbl.textAlignment = UITextAlignmentCenter;
lbl.backgroundColor = [UIColor clearColor];
lbl.textColor = [UIColor whiteColor];
lbl.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:20];
lbl.shadowColor = [UIColor blackColor];
lbl.shadowOffset = CGSizeMake(0,1);
self.navigationItem.titleView = vw;
[self.navigationItem.titleView addSubview:lbl];
What worked for me was to update the titleView frame in the viewDidAppear method.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
UIView *titleView = self.navigationItem.titleView;
CGRect navBarFrame = self.navigationController.navigationBar.frame;
[titleView setFrame:CGRectMake((CGRectGetWidth(navBarFrame) - TitleWidth) / 2, (CGRectGetHeight(navBarFrame) - TitleHeight) / 2, TitleWidth, TitleHeight)];
}