I want to dynamically assign width to a label depending upon the text length to be displayed. The labels are it self being added on uiview. I am using following code but still i am getting label with shorter width.
- (id)initWithFrame:(CGRect)frame OrangeText:(NSString*)orange WhiteText:(NSString*)white {
if ((self = [super initWithFrame:frame])) {
CGSize textSize = [orange sizeWithFont:[UIFont systemFontOfSize:14]];
OrangeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, textSize.width, textSize.height+2)];
OrangeLabel.text = orange;
OrangeLabel.backgroundColor = [UIColor clearColor];
OrangeLabel.textColor = [UIColor orangeColor];
[self addSubview:OrangeLabel];
WhiteLabel = [[UILabel alloc] init];
CGSize whiteTextSize = [white sizeWithFont:[UIFont systemFontOfSize:14]];
WhiteLabel.frame = CGRectMake(OrangeLabel.frame.size.width+35, 5, whiteTextSize.width, whiteTextSize.height);
WhiteLabel.text = white;
WhiteLabel.backgroundColor = [UIColor clearColor];
WhiteLabel.textColor = [UIColor whiteColor];
[self addSubview:WhiteLabel]; // Initialization code
}
return self;
}
I think you are looking for this method
[myLabel sizeToFit];
This should resize the label frame to fit its contents.
Related
I saw a this question and answer and I tried a few options but non worked.
I would like to create a UIPickerView like the one below, (fixed labels inches and feet) but those wouldn't appear:
I create the UIImagePicker like this:
- (void)viewDidLoad
{
_picker = [[UIPickerView alloc] init];
CGRect pickerFrame = CGRectMake(0, 0, 200, 216);
pickerView.frame = pickerFrame;
pickerView.userInteractionEnabled = YES;
pickerView.dataSource = self;
pickerView.hidden = YES;
pickerView.delegate = self;
pickerView.showsSelectionIndicator = YES;
[self.view addSubview:pickerView];
[textField setInputView:pickerView];
textField.delegate = self;
[pickerView removeFromSuperview];
_picker.hidden = YES;
}
- (BOOL) textFieldShouldBeginEditing:(UITextView *)textView
{
if (textView.tag==1){ //field for the uipickerview
_picker.hidden = NO;
[self addPickerLabel:#"Feet" rightX:114 top:342 height:21];
[self addPickerLabel:#"Inches" rightX:241 top:342 height:21];
}
return YES;
}
- (void)addPickerLabel:(NSString *)labelString rightX:(CGFloat)rightX top:(CGFloat)top height:(CGFloat)height {
#define PICKER_LABEL_FONT_SIZE 18
#define PICKER_LABEL_ALPHA 0.7
UIFont *font = [UIFont boldSystemFontOfSize:PICKER_LABEL_FONT_SIZE];
CGFloat x = rightX - [labelString sizeWithFont:font].width;
// White label 1 pixel below, to simulate embossing.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, top + 1, rightX, height)];
label.text = labelString;
label.font = font;
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.opaque = NO;
label.alpha = PICKER_LABEL_ALPHA;
[_picker addSubview:label];
// Actual label.
label = [[UILabel alloc] initWithFrame:CGRectMake(x, top, rightX, height)];
label.text = labelString;
label.font = font;
label.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor clearColor];
label.opaque = NO;
label.alpha = PICKER_LABEL_ALPHA;
[_picker addSubview:label];
}
The picker appears, but without the fixed labels of inches and feet.
What is wrong?
Move this lines to viewDidLoad and try it.Labels need to be added
once.Not always when textfield did begin editing
[self addPickerLabel:#"Feet" rightX:114 top:342 height:21];
[self addPickerLabel:#"Inches" rightX:241 top:342 height:21];
Log the frame of both the label and set it correct if it appears wrong
NSLog(#"%#",NSStringFromCGRect(label.frame));
Your UIPickerView has height of 216, but you put the labels at height 342. This might be the reason you can't see them.
Edit:
Try replacing the lines where you make the labels to
[self addPickerLabel:#"Feet" rightX:114 top:98 height:21];
[self addPickerLabel:#"Inches" rightX:241 top:98 height:21];
I used the already implemented great component:
https://github.com/brunow/ActionSheetPicker2
Which provides a multicolumn picker view and I simply changed the text and the amount of columns
I know this is a noob question but ...I have these labels on a tableview, but the text is completely squished to the left. I want to add a bit of padding. How do I go about it?
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(10,0,300,60)] autorelease];
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
headerLabel.backgroundColor = [UIColor colorWithHexString:[[_months objectAtIndex:section] objectForKey:#"color"]];
headerLabel.font = [UIFont boldSystemFontOfSize:18];
headerLabel.frame = CGRectMake(0,0,400,30);
headerLabel.text = [[_months objectAtIndex:section] objectForKey:#"name"];
headerLabel.textColor = [UIColor whiteColor];
[customView addSubview:headerLabel];
return customView;
}
any help is much appreciated! Thanks!
For a full list of available solutions, see this answer: UILabel text margin
The most flexible approach to add padding to UILabel is to subclass UILabel and add an edgeInsets property. You then set the desired insets and the label will be drawn accordingly.
OSLabel.h
#import <UIKit/UIKit.h>
#interface OSLabel : UILabel
#property (nonatomic, assign) UIEdgeInsets edgeInsets;
#end
OSLabel.m
#import "OSLabel.h"
#implementation OSLabel
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
#end
you can simple add white space at the begin of you text;
[NSString stringWithFormat:#" %#",text];
It is 'evil' way to add 'padding', but it may help.
I found a better way to do this:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = CGRectMake(0, 0, 320, 25);
UIView *customView = [[UIView alloc] initWithFrame:frame];
UILabel *sectionTitle = [[UILabel alloc] init];
[customView addSubview:sectionTitle];
customView.backgroundColor = [UIColor redColor];
frame.origin.x = 10; //move the frame over..this adds the padding!
frame.size.width = self.view.bounds.size.width - frame.origin.x;
sectionTitle.frame = frame;
sectionTitle.text = #"text";
sectionTitle.font = [UIFont boldSystemFontOfSize:17];
sectionTitle.backgroundColor = [UIColor clearColor];
sectionTitle.textColor = [UIColor whiteColor];
[sectionTitle release];
tableView.allowsSelection = NO;
return [customView autorelease];
}
Set the backgroundColor on the customView also
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = tableView.bounds;
frame.size.height = HEADER_HEIGHT;
UIView* customView = [[[UIView alloc] initWithFrame:frame] autorelease];
customView.backgroundColor = [UIColor redColor];
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] autorelease];
// Orientation support
headerLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
headerLabel.backgroundColor = [UIColor redColor];
headerLabel.font = [UIFont boldSystemFontOfSize:18];
headerLabel.text = #"My Text Label";
headerLabel.textColor = [UIColor whiteColor];
[customView addSubview:headerLabel];
return customView;
}
Try not to hardcode magic numbers: (add these to top of file)
#define HEADER_HEIGHT 60.0f
#define LABEL_PADDING 10.0f
Should give this
Try the following & play around with the padding etc.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGFloat headerHeight = 60, padding = 10;
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,320,headerHeight)] autorelease];
customView.backgroundColor = [UIColor colorWithHexString:[[_months objectAtIndex:section] objectForKey:#"color"]];
CGRect frame = CGRectMake(padding,padding,320 - 2*padding,headerHeight-2*padding);
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
headerLabel.font = [UIFont boldSystemFontOfSize:18];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.text = [[_months objectAtIndex:section] objectForKey:#"name"];
headerLabel.textColor = [UIColor whiteColor];
[customView addSubview:headerLabel];
return customView;
}
You can create a subclass of UILabel and override intrinsicContentSize and - (CGSize)sizeThatFits:(CGSize)size:
- (CGSize) intrinsicContentSize
{
CGSize parentSize = [super intrinsicContentSize];
parentSize.width += 2*PADDING_VALUE;
return parentSize;
}
- (CGSize)sizeThatFits:(CGSize)size
{
CGSize parentSize = [super sizeThatFits:size];
parentSize.width += 2*PADDING_VALUE;
return parentSize;
}
True, it's a bit inexact and hackish, but you could always add a space in front of the month name like this:
headerLabel.text = [NSString stringWithFormat:#" %#",
[[_months objectAtIndex:section] objectForKey:#"name"]];
You could use a UITextView instead. I did this in Cocoa but I'm pretty sure it translates to UITextView:
NSTextView *headerLabel = [[[NSTextView alloc] initWithFrame:NSMakeRect(20.0, 20.0, 400.0, 20.0)] autorelease];
[headerLabel setBackgroundColor: [NSColor redColor]];
[headerLabel setString: #"Testing Stuff"];
[headerLabel setTextColor: [NSColor whiteColor]];
NSSize txtPadding;
txtPadding.width = 20.0;
txtPadding.height = 0.0;
[headerLabel setTextContainerInset:txtPadding];
[[mainWin contentView] addSubview:headerLabel];
I have a grouped UITableView. I am trying to make a custom UITableViewCell background:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.contentView.opaque = YES;
self.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"rowbg#2x"]];
//Change Indicator
CGRect rect;
rect = CGRectMake(0, 0, 10, 50);
changeImageIndicator = [[UIImageView alloc] initWithFrame:rect];
[self.contentView addSubview: changeImageIndicator];
//Symbol
rect = CGRectMake(10, 10, 200, 20);
symbolLabel = [[UILabel alloc] initWithFrame:rect];
symbolLabel.textAlignment = UITextAlignmentLeft;
symbolLabel.font = [UIFont fontWithName:#"Arial" size:22];
symbolLabel.textColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
symbolLabel.backgroundColor = [UIColor clearColor];
[self.contentView addSubview: symbolLabel];
//Company
rect = CGRectMake(10, 30, 180, 20);
companyLabel = [[UILabel alloc] initWithFrame:rect];
companyLabel.textAlignment = UITextAlignmentLeft;
companyLabel.font = [UIFont fontWithName:#"Arial" size:13];
companyLabel.adjustsFontSizeToFitWidth = YES;
companyLabel.minimumFontSize = 10.0;
companyLabel.backgroundColor = [UIColor clearColor];
companyLabel.textColor = [UIColor colorWithRed:118.0/255.0 green:118.0/255.0 blue:118.0/255.0 alpha:1.0];
[self.contentView addSubview: companyLabel];
//Price
rect = CGRectMake(190, 10, 100, 20);
priceLabel = [[UILabel alloc] initWithFrame:rect];
priceLabel.textAlignment = UITextAlignmentRight;
priceLabel.font = [UIFont fontWithName:#"Arial" size:20];
priceLabel.textColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
priceLabel.backgroundColor = [UIColor clearColor];
[self.contentView addSubview: priceLabel];
//Change
rect = CGRectMake(190, 30, 100, 20);
changeLabel = [[UILabel alloc] initWithFrame:rect];
changeLabel.textAlignment = UITextAlignmentRight;
changeLabel.font = [UIFont fontWithName:#"Arial" size:15];
changeLabel.textColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
changeLabel.adjustsFontSizeToFitWidth = YES;
changeLabel.backgroundColor = [UIColor clearColor];
changeLabel.minimumFontSize = 10.0; //adjust to preference obviously
[self.contentView addSubview: changeLabel];
}
return self;
}
The background color bleeds past the rounded corners. See image:
How can I make this not bleed?
This works for iOS 3.0 and later:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor redColor];
}
What about self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; ?
This worked for me when nothing else did. Set the background color in IB to the grouped Table view color (default). Then in code, set the color to clearColor. I also have the cells marked opaque=NO and clearsContextBeforeDrawing=NO, but those settings alone didn't change anything until I added the clearColor by code – Bdebeez
self.contentView.superview.opaque = YES;
self.contentView.superview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"rowbg#2x"]];
Have you tried setting the backgroundColor of the backgroundView rather than the contentView?
I had to create a rounded top, middle and button graphic image and set it to the background view of the cell depending on which row it is.
Set the cell background color in the tableView:cellForRowAtIndexPath:
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Gradient.png"]];
I'm working on a UITableView whose cells contain an UIImageView subclass which gets data from a URL and cache images to the iphone disk.
Problem is, event with cached images the scrolling tends to be stuttering. So I searched a bit and found ABTableViewCell ( github.com/enormego/ABTableViewCell ) which is supposed to dramatically improve scrolling smoothness.
But, even with the example provided ( blog.atebits.com/2008/12/fast-scrolling-in-tweetie-with-uitableview ) I don't really get what I am supposed to do.
I tried to do this: I created a class which inherits ABTableViewCell, added some UILabels and the UIImageView as class properties, and implemented methods this way: allocate and initialize subviews (labels, image) in the initialize class method, storing them in static pointers, and then set class properties in - (void)drawContentView:(CGRect)r highlighted:(BOOL)highlighted along with background color setting shown in example. Here's the result:
static AsyncUIImageView* image = nil; // A subclass using ASIHTTPRequest for image loading
static UILabel* label1 = nil;
static UILabel* label2 = nil;
+ (void)initialize {
if (self == [ResultTableViewCell class]) {
image = [[[AsyncUIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 60)] retain];
label1 = [[[UILabel alloc] initWithFrame:CGRectMake(90, 5, 150, 30)] retain];
label1.font = [UIFont fontWithName:#"Helvetica-Bold" size:17];
label1.textColor = [UIColor purpleColor];
label1.backgroundColor = [UIColor clearColor];
label2 = [[[UILabel alloc] initWithFrame:CGRectMake(180, 8, 100, 25)] retain];
label2.font = [UIFont fontWithName:#"Helvetica-Bold" size:12.0];
label2.textColor = [UIColor grayColor];
label2.backgroundColor = [UIColor clearColor];
}
}
- (void)drawContentView:(CGRect)r highlighted:(BOOL)highlighted {
if (self.imageView == nil) {
self.imageView = image;
[self addSubview:image];
self.firstLabel = label1;
[self addSubview:label1];
self.secondLabel = label2;
[self addSubview:label2];
}
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *backgroundColor = [UIColor whiteColor];
UIColor *textColor = [UIColor blackColor];
if (self.selected || self.highlighted) {
backgroundColor = [UIColor clearColor];
textColor = [UIColor whiteColor];
}
[backgroundColor set];
[textColor set];
CGContextFillRect(context, r);
}
This gives me completely black cells, sometimes one has text and image set with correct colors, but its content changes as I scroll down.
Obviously I did not understand what I am supposed to do in drawContentView.
Could someone explain its purpose?
The whole idea is to not add subviews, but to draw the text instead.
Eg.
- (void)drawContentView:(CGRect)r highlighted:(BOOL)highlighted {
[someText drawInRect:r withFont:aFont];
}
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)];
}