Reputation: 15
I have an issue with adding image in the end of the text of the UILabel. How can I detect the size of the text in the label, then add additional space and insert image into it?
Upvotes: 1
Views: 2154
Reputation: 1885
i write a little code for this:
-(void) labelSizeGetter
{
UILabel * mylabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
float heigth=25.0;//max height value of label.
NSString *yourString = @"My great text";
mylabel.font =[UIFont fontWithName:@"Helvetica-Bold" size:12];
[mylabel setText:yourString];
CGSize s = [mylabel.text sizeWithFont:[UIFont systemFontOfSize:12]
constrainedToSize:CGSizeMake(MAXFLOAT,heigth)
lineBreakMode:NSLineBreakByWordWrapping];
// s is a size for text of label. just add 10 pix to width to make it more beautiful.
NSLog(@"%@", NSStringFromCGSize(s));
mylabel.frame=CGRectMake(0, 0, s.width+10, s.height);
[self.view addSubview:mylabel];
UIView * myimage=[[UIView alloc] initWithFrame:CGRectMake(mylabel.frame.origin.x+mylabel.frame.size.width , mylabel.frame.origin.y, 30, 30)];//create your images frame according to frame of your label
myimage.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"arti.png"]];
[self.view addSubview:myimage];
}
i hope it helps
Upvotes: 1
Reputation: 572
UILabel
and UIImageView
[NSString sizeWithFont:]
or similar sizeWith...
methodUIImageView
according to a size of the text Upvotes: 1
Reputation: 13926
There is a category on NSString
that returns the size of a string when rendered with a given font. There are several methods, the most complete on being - (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode
(see Apple Docs).
With that information you might be able to achieve what you want to do.
Upvotes: 0
Reputation: 14118
Here is a code snippet which gives you size adjustable for specific font and specific font size. Accordingly you can set frame for your label and then image view as well.
- (CGSize)getSizeFromText:(NSString*)text {
CGSize constrainedSize;
constrainedSize.width = give maximum allowable width limit;
constrainedSize.height = MAXFLOAT;
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:constrainedSize lineBreakMode: UILineBreakModeWordWrap];
return size;
}
Hope this would help you to solve your problem.
Upvotes: 0
Reputation: 175
If you dont want to use a UIView. Why not check the length of the string in the label. then add some additional space for your image using frame. [UILabel.text length] returns the length.
Upvotes: 1
Reputation: 47059
Best Way is take one UIView
.
And Add Both UILabel
And UIImageView
on This UIView
(give Fram as per your Requirement).
And This UIView
to your MainView of UIViewController
.
Upvotes: 1