Calculate where text begins with center alignment

I have UILabelone that I want to add UIViewexactly where the text starts.

The problem is that the text in the label is centered, so I don’t know how to determine where the actual text starts and where to put this one UIView.

Any idea how I can calculate this thing?

Thank!

+4
source share
4 answers

You can also use

yourLabel.sizeToFit()

to automatically resize the shortcut for the required space. And then read the frame of your label:

yourLabel.frame.size (width or height)
0
source

UIView, UILabel UIView. UILabel . UILabel x, , .

enter image description here

UILabel top, bottom, , , , UIView top, bottom, height, width leading UILabel

+1

: (x, y) 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);

+1

, "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()

rect, .

enter image description here

+1

Source: https://habr.com/ru/post/1651397/


All Articles