0

我有一个标签,里面有一个句子,那是一个字符串。我需要获取字符串中特定单词的 x 坐标。因此,例如,如果我在句子中有一个说“狗跑了”的句子,我需要能够找到 x 和 y 坐标,以及在其上放置 UITextField 的宽度和高度。到目前为止,这是我的代码:

- (void)insertTextFields:(NSString *)string inLabel:(UILabel *)label
{
    CGFloat stringWidth = [self getWidthOfString:string inLabel:label];
    CGFloat stringHeight = label.bounds.size.height;
    CGFloat stringYOrigin = label.bounds.origin.y;
    CGFloat stringXOrigin = [self getXOriginOfString:string fromString:label.text inLabel:label];
    CGRect textFieldRect = CGRectMake(stringXOrigin, stringYOrigin, stringWidth, stringHeight);
    UITextField *textField = [[UITextField alloc] initWithFrame:textFieldRect];
    [label addSubview:textField];
}


- (CGFloat)getWidthOfString:(NSString *)string inLabel:(UITextField *)label
{
    CGFloat maxWidth = CGRectGetMaxX(label.frame);
    CGSize stringSize = [string sizeWithFont:label.font forWidth:maxWidth lineBreakMode:NSLineBreakByCharWrapping];
    CGFloat width = stringSize.width;
    return width;
}

- (CGFloat)getXOriginOfString:(NSString *)string fromString:(NSString *)sentenceString inLabel:(UILabel *)label
{
    CGFloat maxWidth = CGRectGetMaxX(label.frame);
    CGSize sentenceStringSize = [sentenceString sizeWithFont:label.font forWidth:maxWidth lineBreakMode:NSLineBreakByWordWrapping];
    CGSize stringSize = [string sizeWithFont:label.font forWidth:maxWidth lineBreakMode:NSLineBreakByWordWrapping];
    //I have the width of both the individual word and the sentence
    //now I need to find the X coordinate for the individual word inside of the sentence string
    return xOrigin;
}

有人能告诉我我需要做什么来解决这个问题吗?

4

1 回答 1

1

Is that the x position of the start of the word? Just measure the string that precedes the word....

- (CGFloat)getXOriginOfString:(NSString *)string fromString:(NSString *)sentenceString inLabel:(UILabel *)label {

    CGFloat maxWidth = CGRectGetMaxX(label.frame);
    NSRange range = [sentenceString rangeOfString:string];
    NSString *prefix = [sentenceString substringToIndex:range.location];

    return [prefix sizeWithFont:label.font
                       forWidth:maxWidth
                  lineBreakMode:NSLineBreakByWordWrapping].width;
}

The end of the word will be this result + the stringSize in the code you posted. Or maybe I'm misunderstanding the question?

于 2013-04-16T17:26:12.743 回答