Reputation: 297
I have a UILabel
that I want to add a UIView
exactly where the text starts.
The problem is that the text in the label is aligned to the centre so I don't know how to determinate where the actual text starts and where to position this UIView
.
Any idea how can I calculate this thing?
Thank you!
Upvotes: 4
Views: 595
Reputation: 14904
You could also use
yourLabel.sizeToFit()
to automatically resize your label for the space it needs. And then read out the frame of your label with:
yourLabel.frame.size (width or height)
Upvotes: 0
Reputation: 362
you can get text size using "nsattributedstring"
let label = UILabel(frame: CGRectMake(0, 0, 100, 100))
label.text = "dshfk,j"
label.textAlignment = .Center
label.textColor = UIColor.redColor()
let string = label.attributedText
let width = string!.size().width
let height = string!.size().height
let view = UIView(frame: CGRectMake(width, height, width, height))
view.backgroundColor = UIColor.blackColor()
then you can find rect using this ..
sample view
Upvotes: 1
Reputation: 16466
From :How to find the position(x,y) of a letter in UILabel
NSRange range = [@"Good,Morning" rangeOfString:@","];
NSString *prefix = [@"Good,Morning" substringToIndex:range.location];
CGSize size = [prefix sizeWithFont:[UIFont systemFontOfSize:18]];
CGPoint p = CGPointMake(size.width, 0);
NSLog(@"p.x: %f",p.x);
NSLog(@"p.y: %f",p.y);
you can modify it for your purpose
Upvotes: 1
Reputation: 4066
You can use a UIView
container which will wrap the UILabel
and your new UIView
. Then you can let the UILabel
decides the width depending on its content and set it in the center of the container. Once you have this working you can just read the UILabel
x to understand where it starts.
so the UILabel
will have the constraints to top
, bottom
, the height you want and at center to horizontal whereas the little UIView
to top
, bottom
, height
, width
and leading
equal to UILabel
Upvotes: 1