2014-07-02 43 views
1

我有一个UITextField,其中包含一些单词,我想要找出某个索引处单词的边界矩形。在UITextField的索引处查找单词的边界矩形

最好给一些视觉例子,所以我画了一张草图来展示我想要的东西。

比方说,我想“好”(相对)到的UITextField /的UILabel,所以我会调用一些方法像

[self boundingRectForWordAtIndex:2]

的边界矩形,它会给我你在看RECT图片

The Demo Picture

回答

0

我想通了,通过使用从线程的启发下面的代码 :How do I get word wrap information with the new iOS 7 APIs?

- (void)focusOnWordAtIndex:(int)index { 
    NSAttributedString *s = [[NSAttributedString alloc] initWithString:self.textField.text 
                  attributes:@{NSFontAttributeName:self.textField.font}]; 

    NSTextContainer* tc = [[NSTextContainer alloc] initWithSize:CGSizeMake(CGFLOAT_MAX, self.frame.size.height)]; 
    tc.lineFragmentPadding = 0.0; 
    NSLayoutManager* lm = [NSLayoutManager new]; 
    NSTextStorage* tm = [[NSTextStorage alloc] initWithAttributedString:s]; 
    [tm addLayoutManager:lm]; 
    [lm addTextContainer:tc]; 
    CGRect wordRect = [lm boundingRectForGlyphRange:[self rangeForWordAtIndex:index] inTextContainer:tc]; 

// Other code to focus.... 
} 


- (NSRange)rangeForWordAtIndex:(int)index { 

    __block NSRange result; 
    __block int i = 0; 
    NSString *text = self.textField.text; 
    [text enumerateSubstringsInRange:NSMakeRange(0, text.length) 
          options:NSStringEnumerationByWords 
          usingBlock:^(NSString *substring, 
             NSRange substringRange, 
             NSRange enclosingRange, 
             BOOL *stop) 
    { 
     if (i >= index) { 
      result = substringRange; 
      *stop = YES; 
     } 
     i++; 
    }]; 

    return result; 
}