iOS:UILabel字符串中特定文本的CGRect

dze*_*zep 5 nsstring uilabel core-text ios

我想知道字符串在rect中绘制后将是什么帧.

NSString *string = @"This is a sample text.";
UILabel *label = [[UILabel alloc] init];
label.text = string;
// do some setups here
Run Code Online (Sandbox Code Playgroud)

drawInRect:方法中,我想检索特定单词的框架.假设我想知道sample来自This is a sample text.字符串的矩形.

这是一个示例UILabel,我想知道红框内文本的框架.谢谢!

在此输入图像描述

NAN*_*NAV -1

你没有得到 UILabel 中特定单词的框架,你只得到 UILabel 框架,你将字符串分成单词,像这样

NSArray *stringArray = [originalString componentsSeparatedByString:@" "];
Run Code Online (Sandbox Code Playgroud)

为每个 UILabel 添加 UILabel 以及文本和框架

int x=0;
int y=0;

for(int i=0;i<stringArray.count;i++)
    {
        CGSize size =[[stringArray objectAtIndex:i] sizeWithFont:[UIFont fontWithName:@"ChaparralPro-Bold" size:fontSize ]];
        UILabel *label=[[UILabel alloc]init];
         if(x+size.width >320)
           {
             y=y+size.height;
             x=0;
           }
        label.frame = CGRectMake(x,y,size.width,size.height);
        x=x+size.width;
        label.text=[wordsArray objectAtIndex:i];
        label.textColor=UIColorFromRGB(0x3a5670);
        label.font=[UIFont fontWithName:@"ChaparralPro-Bold" size:fontSize];
        label.backgroundColor=[UIColor clearColor];
        [self.view addSubview:label];
        [label release];
}
Run Code Online (Sandbox Code Playgroud)