我有一个带有句子的标签,即一个字符串。我需要获取字符串中特定单词的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;
}
有人能告诉我我需要做些什么来解决这个问题吗?
答案 0 :(得分:1)
这是单词开头的x位置吗?只需测量单词前面的字符串....
- (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;
}
单词的结尾将是此结果+您发布的代码中的stringSize
。或者我可能误解了这个问题?