【问题标题】:iOS : CGRect of a Specific Text in a String of a UILabeliOS:UILabel 字符串中特定文本的 CGRect
【发布时间】:2013-06-13 07:42:34
【问题描述】:

我想知道一个字符串在矩形中绘制后会在哪个帧。

NSString *string = @"This is a sample text.";
UILabel *label = [[UILabel alloc] init];
label.text = string;
// do some setups here

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

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

【问题讨论】:

  • hmm.. 很有趣..你能提供任何关于你想用这个来完成什么的见解吗..?这样人们就可以知道是否有另一种方法可以做到这一点..??这对你有帮助吗..? gist.github.com/erkie/1278483
  • 比如我想在框架上画一个框或者背景图。

标签: ios nsstring uilabel core-text


【解决方案1】:

您可以通过确定一个字符的特定像素来做到这一点

即假设字符“R”在 X 坐标中占用 8 个像素。像这样通过乘以8* number of characters in the label你可以得到帧

【讨论】:

    【解决方案2】:
    1]Create a CGRect.
    
     CountRect=CGRectMake(rect.origin.x,
                             rect.origin.y+22 + (rect.size.height - height)/2,
                             rect.size.width,
                             (rect.size.height - height)/2);
    
    2]set NSString which contain string.(your case only contain sample)
    
      NSString* myNewString;
    
    3]set NSString to CGRect.
    
      [myNewString drawInRect:CountRect 
    withFont:fontlineBreakMode:UILineBreakModeClip alignment:UITextAlignmentCenter];
      [myNewString drawInRect:CountRect withAttributes:attributes];
    

    【讨论】:

      【解决方案3】:

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

      NSArray *stringArray = [originalString componentsSeparatedByString:@" "];
      

      为每个 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];
      }
      

      【讨论】:

        【解决方案4】:

        你可以通过函数获取字符串的大小:

        - (CGSize)sizeWithFont:(UIFont *)font; 
        CGSize wordSize = [@"sample" sizeWithFont:font];
        

        您可以遍历所有单词和换行符并相应地获取每个单词的帧

        【讨论】:

          猜你喜欢
          • 2013-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-08
          • 1970-01-01
          • 1970-01-01
          • 2012-03-30
          • 2015-01-02
          相关资源
          最近更新 更多